Part Number Hot Search : 
8F400 MM1921E 15PQF C1602 BAS16W R5205CND 120EC HER303
Product Description
Full Text Search
 

To Download ATMEGA4060607 Datasheet File

  If you can't view the Datasheet, Please click here to try to view without PDF Reader .  
 
 


  Datasheet File OCR Text:
 Features
* High Performance, Low Power AVR(R) 8-bit Microcontroller * Advanced RISC Architecture
- 124 Powerful Instructions - Most Single Clock Cycle Execution - 32 x 8 General Purpose Working Registers - Fully Static Operation - Up to 1 MIPS Throughput at 1 MHz Nonvolatile Program and Data Memories - 40K Bytes of In-System Self-Programmable Flash, Endurance: 10,000 Write/Erase Cycles - Optional Boot Code Section with Independent Lock Bits In-System Programming by On-chip Boot Program True Read-While-Write Operation - 512 bytes EEPROM, Endurance: 100,000 Write/Erase Cycles - 2K Bytes Internal SRAM - Programming Lock for Software Security On-chip Debugging - Extensive On-chip Debug Support - Available through JTAG interface Battery Management Features - Two, Three, or Four Cells in Series - Deep Under-voltage Protection - Over-current Protection (Charge and Discharge) - Short-circuit Protection (Discharge) - Integrated Cell Balancing FETs - High Voltage Outputs to Drive Charge/Precharge/Discharge FETs Peripheral Features - One 8-bit Timer/Counter with Separate Prescaler, Compare Mode, and PWM - One 16-bit Timer/Counter with Separate Prescaler and Compare Mode - 12-bit Voltage ADC, Eight External and Two Internal ADC Inputs - High Resolution Coulomb Counter ADC for Current Measurements - TWI Serial Interface for SM-Bus - Programmable Wake-up Timer - Programmable Watchdog Timer Special Microcontroller Features - Power-on Reset - On-chip Voltage Regulator - External and Internal Interrupt Sources - Four Sleep Modes: Idle, Power-save, Power-down, and Power-off Packages - 48-pin LQFP Operating Voltage: 4.0 - 25V Maximum Withstand Voltage (High-voltage pins): 28V Temperature Range: -30C to 85C - Speed Grade: 1 MHz
*
*
8-bit Microcontroller with 40K Bytes In-System Programmable Flash ATmega406 Preliminary
*
*
*
* * * *
2548E-AVR-07/06
1. Pin Configurations
Figure 1-1. Pinout ATmega406.
Top View
NNI NI PI PPI VREFGND VREF NV PV1 PV2 PV3 PV4 GND 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 13 14 15 16 17 18 19 20 21 22 23 24
SGND (ADC0/PCINT0) PA0 (ADC1/PCINT1) PA1 (ADC2/PCINT2) PA2 (ADC3/PCINT3) PA3 VREG VCC GND (ADC4/INT0/PCINT4) PA4 (INT1/PCINT5) PA5 (INT2/PCINT6) PA6 (INT3/PCINT7) PA7
1 2 3 4 5 6 7 8 9 10 11 12
PVT OD VFET OC OPC BATT PC0 GND PD1 PD0 (T0) PB7 (OC0B/PCINT15) PB6 (OC0A/PCINT14)
1.1
Disclaimer
Typical values contained in this datasheet are based on simulations and characterization of other AVR microcontrollers manufactured on the same process technology. Min and Max values will be available after the device is characterized.
2
ATmega406
2548E-AVR-07/06
RESET XTAL1 XTAL2 GND (TDO/PCINT8) PB0 (TDI/PCINT9) PB1 (TMS/PCINT10) PB2 (TCK/PCINT11) PB3 (PCINT12) PB4 (PCINT13) PB5 SCL SDA
ATmega406
2. Overview
The ATmega406 is a low-power CMOS 8-bit microcontroller based on the AVR enhanced RISC architecture. By executing powerful instructions in a single clock cycle, the ATmega406 achieves throughputs approaching 1 MIPS at 1 MHz.
2.1
Block Diagram
Block Diagram
PD1..0 PB7..0
Figure 2-1.
XTAL1 Oscillator Circuits / Clock Generation XTAL2 Watchdog Oscillator Watchdog Timer Flash RESET Power Supervision POR & RESET SRAM 16 bit T/C1 PORTD (2) PORTB (8) OPC OC OD PPI NNI PVT PV4 PV3 PV2 PV1 NV SGND
FET Control Battery Protection
Wake-Up Timer
JTAG
8 bit T/C0
Cell Balancing
VCC
Voltage ADC
CPU
EEPROM
Voltage Reference
VREF VREFGND PI NI
GND BATT Charger Detect Coulumb Counter ADC DATA BUS
VFET VREG
Voltage Regulator
TWI
PORTC (1)
PORTA (8) PA3..0
SCL
SCA
PC0
PA7..0
The ATmega406 provides the following features: a Voltage Regulator, dedicated Battery Protection Circuitry, integrated cell balancing FETs, high-voltage analog front-end, and an MCU with two ADCs with On-chip voltage reference for battery fuel gauging. The voltage regulator operates at a wide range of voltages, 4.0 - 25 volts. This voltage is regulated to a constant supply voltage of nominally 3.3 volts for the integrated logic and analog functions. The battery protection monitors the battery voltage and charge/discharge current to detect illegal conditions and protect the battery from these when required. The illegal conditions are deep under-voltage during discharging, short-circuit during discharging and over-current during charging and discharging.
3
2548E-AVR-07/06
The integrated cell balancing FETs allow cell balancing algorithms to be implemented in software. The MCU provides the following features: 40K bytes of In-System Programmable Flash with Read-While-Write capabilities, 512 bytes EEPROM, 2K byte SRAM, 32 general purpose working registers, 18 general purpose I/O lines, 11 high-voltage I/O lines, a JTAG Interface for On-chip Debugging support and programming, two flexible Timer/Counters with PWM and compare modes, one Wake-up Timer, an SM-Bus compliant TWI module, internal and external interrupts, a 12-bit Sigma Delta ADC for voltage and temperature measurements, a high resolution Sigma Delta ADC for Coulomb Counting and instantaneous current measurements, a programmable Watchdog Timer with internal Oscillator, and four software selectable power saving modes. The AVR core combines a rich instruction set with 32 general purpose working registers. All the 32 registers are directly connected to the Arithmetic Logic Unit (ALU), allowing two independent registers to be accessed in one single instruction executed in one clock cycle. The resulting architecture is more code efficient while achieving throughputs up to ten times faster than conventional CISC microcontrollers. The Idle mode stops the CPU while allowing the other chip function to continue functioning. The Power-down mode allows the voltage regulator, battery protection, regulator current detection, Watchdog Timer, and Wake-up Timer to operate, while disabling all other chip functions until the next Interrupt or Hardware Reset. In Power-save mode, the Wake-up Timer and Coulomb Counter ADC continues to run. The device is manufactured using Atmel's high voltage high density non-volatile memory technology. The On-chip ISP Flash allows the program memory to be reprogrammed In-System, by a conventional non-volatile memory programmer or by an On-chip Boot program running on the AVR core. The Boot program can use any interface to download the application program in the Application Flash memory. Software in the Boot Flash section will continue to run while the Application Flash section is updated, providing true Read-While-Write operation. By combining an 8-bit RISC CPU with In-System Self-Programmable Flash, fuel gauging ADCs, dedicated battery protection circuitry, Cell Balancing FETs, and a voltage regulator on a monolithic chip, the Atmel ATmega406 is a powerful microcontroller that provides a highly flexible and cost effective solution for Li-ion Smart Battery applications. The ATmega406 AVR is supported with a full suite of program and system development tools including: C Compilers, Macro Assemblers, Program Debugger/Simulators, and On-chip Debugger.
4
ATmega406
2548E-AVR-07/06
ATmega406
2.2
2.2.1
Pin Descriptions
VFET High voltage supply pin. This pin is used as supply for the internal voltage regulator, described in "Voltage Regulator" on page 114. In addition the voltage level on this pin is monitored by the battery protection circuit, for deep-under-voltage protection. For details, see "Battery Protection" on page 125.
2.2.2
VCC Digital supply voltage. Normally connected to VREG.
2.2.3
VREG Output from the internal Voltage Regulator. Used for external decoupling to ensure stable regulator operation. For details, see "Voltage Regulator" on page 114.
2.2.4
VREF Internal Voltage Reference for external decoupling. For details, see "Voltage Reference and Temperature Sensor" on page 121.
2.2.5
VREFGND Ground for decoupling of Internal Voltage Reference. For details, see "Voltage Reference and Temperature Sensor" on page 121.
2.2.6
GND Ground
2.2.7
SGND Signal ground pin, used as reference for Voltage-ADC conversions. For details, see "Voltage ADC - 10-channel General Purpose 12-bit Sigma-Delta ADC" on page 116.
2.2.8
Port A (PA7:PA0) PA3:PA0 serves as the analog inputs to the Voltage A/D Converter. Port A also serves as a low-voltage 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). As inputs, Port A pins that are externally pulled low will source current if the pull-up resistors are activated. The Port A pins are tri-stated when a reset condition becomes active, even if the clock is not running. Port A also serves the functions of various special features of the ATmega406 as listed in "Alternate Functions of Port A" on page 68.
2.2.9
Port B (PB7:PB0) Port B is a low-voltage 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). As inputs, Port B pins that are externally pulled low will source current if the pull-up resistors are activated. The Port B pins are tri-stated when a reset condition becomes active, even if the clock is not running. Port B also serves the functions of various special features of the ATmega406 as listed in "Alternate Functions of Port B" on page 70.
5
2548E-AVR-07/06
2.2.10
Port C (PC0) Port C is a high voltage Open Drain output port.
2.2.11
Port D (PD1:PD0) Port D is a low-voltage 2-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). As inputs, Port D pins that are externally pulled low will source current if the pull-up resistors are activated. The Port D pins are tri-stated when a reset condition becomes active, even if the clock is not running. Port D also serves the functions of various special features of the ATmega406 as listed in "Alternate Functions of Port D" on page 72.
2.2.12
SCL SMBUS clock, Open Drain bidirectional pin.
2.2.13
SDA SMBUS data, Open Drain bidirectional pin.
2.2.14
OC/OD/OPC High voltage output to drive external Charge/Discharge/Pre-charge FETs. For details, see "FET Control" on page 133.
2.2.15
PI/NI Unfiltered positive/negative input from external current sense resistor, used by the battery protection circuit, for over-current and short-circuit detection. For details, see "Battery Protection" on page 125.
2.2.16
PPI/NNI Filtered positive/negative input from external current sense resistor, used to by the Coulomb Counter ADC to measure charge/discharge currents flowing in the battery pack. For details, see "Coulomb Counter - Dedicated Fuel Gauging Sigma-delta ADC" on page 106.
2.2.17
NV/PV1/PV2/PV3/PV4 NV, PV1, PV2, PV3, and PV4 are the inputs for battery cells 1, 2, 3 and 4, used by the Voltage ADC to measure each cell voltage. For details, see "Voltage ADC - 10-channel General Purpose 12-bit Sigma-Delta ADC" on page 116. PVT PVT defines the pull-up level for the OD output.
2.2.18
2.2.19
BATT Input for detecting when a charger is connected. This pin also defines the pull-up level for OC and OPC outputs.
2.2.20
RESET Reset input. A low level on this pin for longer than the minimum pulse length will generate a reset, even if the clock is not running. The minimum pulse length is given in Table 11 on page 38. Shorter pulses are not guaranteed to generate a reset.
6
ATmega406
2548E-AVR-07/06
ATmega406
2.2.21 XTAL1 Input to the inverting Oscillator amplifier. 2.2.22 XTAL2 Output from the inverting Oscillator amplifier.
3. Resources
A comprehensive set of development tools, application notes and datasheets are available for download on http://www.atmel.com/avr.
4. About Code Examples
This documentation contains simple code examples that briefly show how to use various parts of the device. These code examples assume that the part specific header file is included before compilation. Be aware that not all C compiler vendors include bit definitions in the header files and interrupt handling in C is compiler dependent. Please confirm with the C compiler documentation for more details. For I/O Registers located in extended I/O map, "IN", "OUT", "SBIS", "SBIC", "CBI", and "SBI" instructions must be replaced with instructions that allow access to extended I/O. Typically "LDS" and "STS" combined with "SBRS", "SBRC", "SBR", and "CBR".
7
2548E-AVR-07/06
5. AVR CPU Core
5.1 Introduction
This section discusses the AVR core architecture in general. The main function of the CPU core is to ensure correct program execution. The CPU must therefore be able to access memories, perform calculations, control peripherals, and handle interrupts.
5.2
Architectural Overview
Figure 5-1. Block Diagram of the AVR Architecture
Data Bus 8-bit
Flash Program Memory
Program Counter
Status and Control
Instruction Register
32 x 8 General Purpose Registrers
Interrupt Unit Watchdog Timer
Indirect Addressing
Instruction Decoder
Direct Addressing
ALU I/O Module1
Control Lines
I/O Module 2
Data SRAM
I/O Module n
EEPROM
I/O Lines
In order to maximize performance and parallelism, the AVR uses a Harvard architecture - with separate memories and buses for program and data. Instructions in the program memory are executed with a single level pipelining. While one instruction is being executed, the next instruction is pre-fetched from the program memory. This concept enables instructions to be executed in every clock cycle. The program memory is In-System Reprogrammable Flash memory.
8
ATmega406
2548E-AVR-07/06
ATmega406
The fast-access Register File contains 32 x 8-bit general purpose working registers with a single clock cycle access time. This allows single-cycle Arithmetic Logic Unit (ALU) operation. In a typical ALU operation, two operands are output from the Register File, the operation is executed, and the result is stored back in the Register File - in one clock cycle. Six of the 32 registers can be used as three 16-bit indirect address register pointers for Data Space addressing - enabling efficient address calculations. One of the these address pointers can also be used as an address pointer for look up tables in Flash program memory. These added function registers are the 16-bit X-, Y-, and Z-register, described later in this section. The ALU supports arithmetic and logic operations between registers or between a constant and a register. Single register operations can also be executed in the ALU. After an arithmetic operation, the Status Register is updated to reflect information about the result of the operation. Program flow is provided by conditional and unconditional jump and call instructions, able to directly address the whole address space. Most AVR instructions have a single 16-bit word format. Every program memory address contains a 16- or 32-bit instruction. Program Flash memory space is divided in two sections, the Boot Program section and the Application Program section. Both sections have dedicated Lock bits for write and read/write protection. The SPM instruction that writes into the Application Flash memory section must reside in the Boot Program section. During interrupts and subroutine calls, the return address Program Counter (PC) is stored on the Stack. The Stack is effectively allocated in the general data SRAM, and consequently the Stack size is only limited by the total SRAM size and the usage of the SRAM. All user programs must initialize the SP in the Reset routine (before subroutines or interrupts are executed). The Stack Pointer (SP) is read/write accessible in the I/O space. The data SRAM can easily be accessed through the five different addressing modes supported in the AVR architecture. The memory spaces in the AVR architecture are all linear and regular memory maps. A flexible interrupt module has its control registers in the I/O space with an additional Global Interrupt Enable bit in the Status Register. All interrupts have a separate Interrupt Vector in the Interrupt Vector table. The interrupts have priority in accordance with their Interrupt Vector position. The lower the Interrupt Vector address, the higher the priority. The I/O memory space contains 64 addresses for CPU peripheral functions as Control Registers, SPI, and other I/O functions. The I/O Memory can be accessed directly, or as the Data Space locations following those of the Register File, 0x20 - 0x5F. In addition, the ATmega406 has Extended I/O space from 0x60 - 0xFF in SRAM where only the ST/STS/STD and LD/LDS/LDD instructions can be used.
5.3
ALU - Arithmetic Logic Unit
The high-performance AVR ALU operates in direct connection with all the 32 general purpose working registers. Within a single clock cycle, arithmetic operations between general purpose registers or between a register and an immediate are executed. The ALU operations are divided into three main categories - arithmetic, logical, and bit-functions. Some implementations of the architecture also provide a powerful multiplier supporting both signed/unsigned multiplication and fractional format. See the "Instruction Set" section for a detailed description.
9
2548E-AVR-07/06
5.4
Status Register
The Status Register contains information about the result of the most recently executed arithmetic instruction. This information can be used for altering program flow in order to perform conditional operations. Note that the Status Register is updated after all ALU operations, as specified in the "AVR Instruction Set" description. This will in many cases remove the need for using the dedicated compare instructions, resulting in faster and more compact code. The Status Register is not automatically stored when entering an interrupt routine and restored when returning from an interrupt. This must be handled by software.
5.4.1
SREG - AVR Status Register The AVR Status Register - SREG - is defined as:
Bit 0x3F (0x5F) Read/Write Initial Value 7 I R/W 0 6 T R/W 0 5 H R/W 0 4 S R/W 0 3 V R/W 0 2 N R/W 0 1 Z R/W 0 0 C R/W 0 SREG
* Bit 7 - I: Global Interrupt Enable The Global Interrupt Enable bit must be set for the interrupts to be enabled. The individual interrupt enable control is then performed in separate control registers. If the Global Interrupt Enable Register is cleared, none of the interrupts are enabled independent of the individual interrupt enable settings. The I-bit is cleared by hardware after an interrupt has occurred, and is set by the RETI instruction to enable subsequent interrupts. The I-bit can also be set and cleared by the application with the SEI and CLI instructions, as described in the "AVR Instruction Set" description. * Bit 6 - T: Bit Copy Storage The Bit Copy instructions BLD (Bit LoaD) and BST (Bit STore) use the T-bit as source or destination for the operated bit. A bit from a register in the Register File can be copied into T by the BST instruction, and a bit in T can be copied into a bit in a register in the Register File by the BLD instruction. * Bit 5 - H: Half Carry Flag The Half Carry Flag H indicates a Half Carry in some arithmetic operations. Half Carry Is useful in BCD arithmetic. See the "AVR Instruction Set" for detailed information. * Bit 4 - S: Sign Bit, S = N V The S-bit is always an exclusive or between the negative flag N and the Two's Complement Overflow Flag V. See the "AVR Instruction Set" for detailed information. * Bit 3 - V: Two's Complement Overflow Flag The Two's Complement Overflow Flag V supports two's complement arithmetics. See the "AVR Instruction Set" for detailed information. * Bit 2 - N: Negative Flag The Negative Flag N indicates a negative result in an arithmetic or logic operation. See the "AVR Instruction Set" for detailed information.
10
ATmega406
2548E-AVR-07/06
ATmega406
* Bit 1 - Z: Zero Flag The Zero Flag Z indicates a zero result in an arithmetic or logic operation. See the "AVR Instruction Set" for detailed information. * Bit 0 - C: Carry Flag The Carry Flag C indicates a carry in an arithmetic or logic operation. See the "AVR Instruction Set" for detailed information.
5.5
General Purpose Register File
The Register File is optimized for the AVR Enhanced RISC instruction set. In order to achieve the required performance and flexibility, the following input/output schemes are supported by the Register File: * One 8-bit output operand and one 8-bit result input * Two 8-bit output operands and one 8-bit result input * Two 8-bit output operands and one 16-bit result input * One 16-bit output operand and one 16-bit result input Figure 5-2 shows the structure of the 32 general purpose working registers in the CPU. Figure 5-2. AVR CPU General Purpose Working Registers
7 R0 R1 R2 ... R13 General Purpose Working Registers R14 R15 R16 R17 ... R26 R27 R28 R29 R30 R31 0x1A 0x1B 0x1C 0x1D 0x1E 0x1F X-register Low Byte X-register High Byte Y-register Low Byte Y-register High Byte Z-register Low Byte Z-register High Byte 0x0D 0x0E 0x0F 0x10 0x11 0 Addr. 0x00 0x01 0x02
Most of the instructions operating on the Register File have direct access to all registers, and most of them are single cycle instructions. As shown in Figure 5-2, each register is also assigned a data memory address, mapping them directly into the first 32 locations of the user Data Space. Although not being physically implemented as SRAM locations, this memory organization provides great flexibility in access of the registers, as the X-, Y- and Z-pointer registers can be set to index any register in the file.
11
2548E-AVR-07/06
5.5.1
The X-register, Y-register, and Z-register The registers R26:R31 have some added functions to their general purpose usage. These registers are 16-bit address pointers for indirect addressing of the data space. The three indirect address registers X, Y, and Z are defined as described in Figure 5-3. Figure 5-3. The X-, Y-, and Z-registers
15 X-register 7 R27 (0x1B) XH 0 7 R26 (0x1A) XL 0 0
15 Y-register 7 R29 (0x1D)
YH 0 7 R28 (0x1C)
YL
0 0
15 Z-register 7 R31 (0x1F)
ZH 0 7 R30 (0x1E)
ZL 0
0
In the different addressing modes these address registers have functions as fixed displacement, automatic increment, and automatic decrement (see the "AVR Instruction Set" description for details).
5.6
Stack Pointer
The Stack is mainly used for storing temporary data, for storing local variables and for storing return addresses after interrupts and subroutine calls. The Stack Pointer Register always points to the top of the Stack. Note that the Stack is implemented as growing from higher memory locations to lower memory locations. This implies that a Stack PUSH command decreases the Stack Pointer. The Stack Pointer points to the data SRAM Stack area where the Subroutine and Interrupt Stacks are located. This Stack space in the data SRAM must be defined by the program before any subroutine calls are executed or interrupts are enabled. The Stack Pointer must be set to point above 0x100. The Stack Pointer is decremented by one when data is pushed onto the Stack with the PUSH instruction, and it is decremented by two when the return address is pushed onto the Stack with subroutine call or interrupt. The Stack Pointer is incremented by one when data is popped from the Stack with the POP instruction, and it is incremented by two when data is popped from the Stack with return from subroutine RET or return from interrupt RETI. The AVR Stack Pointer is implemented as two 8-bit registers in the I/O space. The number of bits actually used is implementation dependent. Note that the data space in some implementations of the AVR architecture is so small that only SPL is needed. In this case, the SPH Register will not be present.
12
ATmega406
2548E-AVR-07/06
ATmega406
5.6.1 SPH and SPL - Stack Pointer Register
Bit 0x3E (0x5E) 0x3D (0x5D) 15 SP15 SP7 7 Read/Write R/W R/W Initial Value 0 0 14 SP14 SP6 6 R/W R/W 0 0 13 SP13 SP5 5 R/W R/W 0 0 12 SP12 SP4 4 R/W R/W 0 0 11 SP11 SP3 3 R/W R/W 0 0 10 SP10 SP2 2 R/W R/W 0 0 9 SP9 SP1 1 R/W R/W 0 0 8 SP8 SP0 0 R/W R/W 0 0 SPH SPL
5.7
Instruction Execution Timing
This section describes the general access timing concepts for instruction execution. The AVR CPU is driven by the CPU clock clkCPU, directly generated from the selected clock source for the chip. No internal clock division is used. Figure 5-4 shows the parallel instruction fetches and instruction executions enabled by the Harvard architecture and the fast-access Register File concept. This is the basic pipelining concept to obtain up to 1 MIPS per MHz with the corresponding unique results for functions per cost, functions per clocks, and functions per power-unit. Figure 5-4. The Parallel Instruction Fetches and Instruction Executions
T1 T2 T3 T4
clkCPU 1st Instruction Fetch 1st Instruction Execute 2nd Instruction Fetch 2nd Instruction Execute 3rd Instruction Fetch 3rd Instruction Execute 4th Instruction Fetch
Figure 5-5 shows the internal timing concept for the Register File. In a single clock cycle an ALU operation using two register operands is executed, and the result is stored back to the destination register. Figure 5-5. Single Cycle ALU Operation
T1 T2 T3 T4
clkCPU Total Execution Time Register Operands Fetch ALU Operation Execute Result Write Back
13
2548E-AVR-07/06
5.8
Reset and Interrupt Handling
The AVR provides several different interrupt sources. These interrupts and the separate Reset Vector each have a separate program vector in the program memory space. All interrupts are assigned individual enable bits which must be written logic one together with the Global Interrupt Enable bit in the Status Register in order to enable the interrupt. Depending on the Program Counter value, interrupts may be automatically disabled when Boot Lock bits BLB02 or BLB12 are programmed. This feature improves software security. See the section "Memory Programming" on page 195 for details. The lowest addresses in the program memory space are by default defined as the Reset and Interrupt Vectors. The complete list of vectors is shown in "Interrupts" on page 51. The list also determines the priority levels of the different interrupts. The lower the address the higher is the priority level. RESET has the highest priority. The Interrupt Vectors can be moved to the start of the Boot Flash section by setting the IVSEL bit in the MCU Control Register (MCUCR). Refer to "Interrupts" on page 51 for more information. The Reset Vector can also be moved to the start of the Boot Flash section by programming the BOOTRST Fuse, see "Boot Loader Support - ReadWhile-Write Self-Programming" on page 178. When an interrupt occurs, the Global Interrupt Enable I-bit is cleared and all interrupts are disabled. The user software can write logic one to the I-bit to enable nested interrupts. All enabled interrupts can then interrupt the current interrupt routine. The I-bit is automatically set when a Return from Interrupt instruction - RETI - is executed. There are basically two types of interrupts. The first type is triggered by an event that sets the interrupt flag. For these interrupts, the Program Counter is vectored to the actual Interrupt Vector in order to execute the interrupt handling routine, and hardware clears the corresponding interrupt flag. Interrupt flags can also be cleared by writing a logic one to the flag bit position(s) to be cleared. If an interrupt condition occurs while the corresponding interrupt enable bit is cleared, the interrupt flag will be set and remembered until the interrupt is enabled, or the flag is cleared by software. Similarly, if one or more interrupt conditions occur while the Global Interrupt Enable bit is cleared, the corresponding interrupt flag(s) will be set and remembered until the Global Interrupt Enable bit is set, and will then be executed by order of priority. The second type of interrupts will trigger as long as the interrupt condition is present. These interrupts do not necessarily have interrupt flags. If the interrupt condition disappears before the interrupt is enabled, the interrupt will not be triggered. When the AVR exits from an interrupt, it will always return to the main program and execute one more instruction before any pending interrupt is served. Note that the Status Register is not automatically stored when entering an interrupt routine, nor restored when returning from an interrupt routine. This must be handled by software. When using the CLI instruction to disable interrupts, the interrupts will be immediately disabled. No interrupt will be executed after the CLI instruction, even if it occurs simultaneously with the
14
ATmega406
2548E-AVR-07/06
ATmega406
CLI instruction. The following example shows how this can be used to avoid interrupts during the timed EEPROM write sequence. Assembly Code Example
in r16, SREG cli sbi EECR, EEMWE sbi EECR, EEWE out SREG, r16 ; restore SREG value (I-bit) ; store SREG value ; start EEPROM write ; disable interrupts during timed sequence
C Code Example
char cSREG; cSREG = SREG; /* store SREG value */ /* disable interrupts during timed sequence */ _CLI(); EECR |= (1<When using the SEI instruction to enable interrupts, the instruction following SEI will be executed before any pending interrupts, as shown in this example. Assembly Code Example
sei ; set Global Interrupt Enable sleep; enter sleep, waiting for interrupt ; note: will enter sleep before any pending ; interrupt(s)
C Code Example
_SEI(); /* set Global Interrupt Enable */ _SLEEP(); /* enter sleep, waiting for interrupt */ /* note: will enter sleep before any pending interrupt(s) */
5.8.1
Interrupt Response Time The interrupt execution response for all the enabled AVR interrupts is four clock cycles minimum. After four clock cycles the program vector address for the actual interrupt handling routine is executed. During this four clock cycle period, the Program Counter is pushed onto the Stack. The vector is normally a jump to the interrupt routine, and this jump takes three clock cycles. If an interrupt occurs during execution of a multi-cycle instruction, this instruction is completed before the interrupt is served. If an interrupt occurs when the MCU is in sleep mode, the interrupt execution response time is increased by four clock cycles. This increase comes in addition to the start-up time from the selected sleep mode. A return from an interrupt handling routine takes four clock cycles. During these four clock cycles, the Program Counter (two bytes) is popped back from the Stack, the Stack Pointer is incremented by two, and the I-bit in SREG is set.
15
2548E-AVR-07/06
6. AVR Memories
This section describes the different memories in the ATmega406. The AVR architecture has two main memory spaces, the Data Memory and the Program Memory space. In addition, the ATmega406 features an EEPROM Memory for data storage. All three memory spaces are linear and regular.
6.1
In-System Reprogrammable Flash Program Memory
The ATmega406 contains 40K bytes On-chip In-System Reprogrammable Flash memory for program storage. Since all AVR instructions are 16 or 32 bits wide, the Flash is organized as 20K x 16. For software security, the Flash Program memory space is divided into two sections, Boot Program section and Application Program section. The Flash memory has an endurance of at least 10,000 write/erase cycles. The ATmega406 Program Counter (PC) is 15 bits wide, thus addressing the 20K program memory locations. The operation of Boot Program section and associated Boot Lock bits for software protection are described in detail in "Boot Loader Support - Read-While-Write Self-Programming" on page 178. "Memory Programming" on page 195 contains a detailed description on Flash data serial downloading. Constant tables can be allocated within the entire program memory address space (see the LPM - Load Program Memory instruction description). Timing diagrams for instruction fetch and execution are presented in "Instruction Execution Timing" on page 13. Figure 6-1. Program Memory Map
Program Memory 0x0000
Application Flash Section
Boot Flash Section 0x4FFF
16
ATmega406
2548E-AVR-07/06
ATmega406
6.2 SRAM Data Memory
Figure 6-2 shows how the ATmega406 SRAM Memory is organized. The ATmega406 is a complex microcontroller with more peripheral units than can be supported within the 64 locations reserved in the Opcode for the IN and OUT instructions. For the Extended I/O space from 0x60 - 0xFF in SRAM, only the ST/STS/STD and LD/LDS/LDD instructions can be used. The lower 2,304 data memory locations address both the Register File, the I/O memory, Extended I/O memory, and the internal data SRAM. The first 32 locations address the Register File, the next 64 location the standard I/O memory, then 160 locations of Extended I/O memory, and the next 2,048 locations address the internal data SRAM. The five different addressing modes for the data memory cover: Direct, Indirect with Displacement, Indirect, Indirect with Pre-decrement, and Indirect with Post-increment. In the Register File, registers R26 to R31 feature the indirect addressing pointer registers. The direct addressing reaches the entire data space. The Indirect with Displacement mode reaches 63 address locations from the base address given by the Y- or Z-register. When using register indirect addressing modes with automatic pre-decrement and post-increment, the address registers X, Y, and Z are decremented or incremented. The 32 general purpose working registers, 64 I/O Registers, 160 Extended I/O Registers, and the 2,048 bytes of internal data SRAM in the ATmega406 are all accessible through all these addressing modes. The Register File is described in "General Purpose Register File" on page 11. Figure 6-2. Data Memory Map
Data Memory
32 Registers 64 I/O Registers 160 Ext I/O Reg. Internal SRAM (2048 x 8) 0x08FF 0x0000 - 0x001F 0x0020 - 0x005F 0x0060 - 0x00FF 0x0100
17
2548E-AVR-07/06
6.2.1
Data Memory Access Times This section describes the general access timing concepts for internal memory access. The internal data SRAM access is performed in two clkCPU cycles as described in Figure 6-3. Figure 6-3. On-chip Data SRAM Access Cycles
T1 T2 T3
clkCPU Address Data WR Data RD
Compute Address Address valid
Memory Access Instruction
Next Instruction
6.3
EEPROM Data Memory
The ATmega406 contains 512 bytes of data EEPROM memory. It is organized as a separate data space, in which single bytes can be read and written. The EEPROM has an endurance of at least 100,000 write/erase cycles. The access between the EEPROM and the CPU is described in the following, specifying the EEPROM Address Registers, the EEPROM Data Register, and the EEPROM Control Register. For a detailed description of Serial and Parallel data downloading to the EEPROM, see page 211 and page 199 respectively.
6.3.1
EEPROM Read/Write Access The EEPROM Access Registers are accessible in the I/O space. The write access time for the EEPROM is given in Table 6-1. A self-timing function, however, lets the user software detect when the next byte can be written. If the user code contains instructions that write the EEPROM, some precautions must be taken. In order to prevent unintentional EEPROM writes, a specific write procedure must be followed. Refer to the description of the EEPROM Control Register for details on this. When the EEPROM is read, the CPU is halted for four clock cycles before the next instruction is executed. When the EEPROM is written, the CPU is halted for two clock cycles before the next instruction is executed.
18
ATmega406
2548E-AVR-07/06
Read
Write
ATmega406
6.3.2 EEARH and EEARL - The EEPROM Address Register
Bit 0x22 (0x42) 0x21 (0x41) 15 - EEAR7 7 Read/Write R R/W Initial Value 0 X 14 - EEAR6 6 R R/W 0 X 13 - EEAR5 5 R R/W 0 X 12 - EEAR4 4 R R/W 0 X 11 - EEAR3 3 R R/W 0 X 10 - EEAR2 2 R R/W 0 X 9 - EEAR1 1 R R/W 0 X 8 EEAR8 EEAR0 0 R/W R/W X X EEARH EEARL
* Bits 15:9 - Res: Reserved Bits These bits are reserved bits in the ATmega406 and will always read as zero. * Bits 8:0 - EEAR8:0: EEPROM Address The EEPROM Address Registers - EEARH and EEARL specify the EEPROM address in the 512 bytes EEPROM space. The EEPROM data bytes are addressed linearly between 0 and 511. The initial value of EEAR is undefined. A proper value must be written before the EEPROM may be accessed. 6.3.3 EEDR - The EEPROM Data Register
Bit 0x20 (0x40) Read/Write Initial Value 7 MSB R/W 0 R/W 0 R/W 0 R/W 0 R/W 0 R/W 0 R/W 0 6 5 4 3 2 1 0 LSB R/W 0 EEDR
* Bits 7:0 - EEDR7:0: EEPROM Data For the EEPROM write operation, the EEDR Register contains the data to be written to the EEPROM in the address given by the EEAR Register. For the EEPROM read operation, the EEDR contains the data read out from the EEPROM at the address given by EEAR. 6.3.4 EECR - The EEPROM Control Register
Bit 0x1F (0x3F) Read/Write Initial Value 7 - R 0 6 - R 0 5 EEPM1 R/W X 4 EEPM0 R/W X 3 EERIE R/W 0 2 EEMPE R/W 0 1 EEPE R/W X 0 EERE R/W 0 EECR
* Bits 7:6 - Res: Reserved Bits These bits are reserved bits in the ATmega406 and will always read as zero. * Bits 5:4 - EEPM1 and EEPM0: EEPROM Programming Mode Bits The EEPROM Programming mode bit setting defines which programming action that will be triggered when writing EEPE. It is possible to program data in one atomic operation (erase the old value and program the new value) or to split the Erase and Write operations in two different operations. The Programming times for the different modes are shown in Table 6-1. While EEPE is set, any write to EEPMn will be ignored. During reset, the EEPMn bits will be reset to 0b00 unless the EEPROM is busy programming.
19
2548E-AVR-07/06
Table 6-1.
EEPM1 0 0 1 1
EEPROM Mode Bits
EEPM0 0 1 0 1 Programming Time 3.4 ms 1.8 ms 1.8 ms - Operation Erase and Write in one operation (Atomic Operation) Erase Only Write Only Reserved for future use
* Bit 3 - EERIE: EEPROM Ready Interrupt Enable Writing EERIE to one enables the EEPROM Ready Interrupt if the I bit in SREG is set. Writing EERIE to zero disables the interrupt. The EEPROM Ready interrupt generates a constant interrupt when EEPE is cleared. * Bit 2 - EEMPE: EEPROM Master Programming Enable The EEMPE bit determines whether setting EEPE to one causes the EEPROM to be written. When EEMPE is set, setting EEPE within four clock cycles will write data to the EEPROM at the selected address If EEMPE is zero, setting EEPE will have no effect. When EEMPE has been written to one by software, hardware clears the bit to zero after four clock cycles. See the description of the EEPE bit for an EEPROM write procedure. * Bit 1 - EEPE: EEPROM Programming Enable The EEPROM Write Enable Signal EEPE is the write strobe to the EEPROM. When address and data are correctly set up, the EEPE bit must be written to one to write the value into the EEPROM. The EEMPE bit must be written to one before a logical one is written to EEPE, otherwise no EEPROM write takes place. The following procedure should be followed when writing the EEPROM (the order of steps 3 and 4 is not essential): 1. Wait until EEPE becomes zero. 2. Wait until SELFPRGEN in SPMCSR becomes zero. 3. Write new EEPROM address to EEAR (optional). 4. Write new EEPROM data to EEDR (optional). 5. Write a logical one to the EEMPE bit while writing a zero to EEPE in EECR. 6. Within four clock cycles after setting EEMPE, write a logical one to EEPE. The EEPROM can not be programmed during a CPU write to the Flash memory. The software must check that the Flash programming is completed before initiating a new EEPROM write. Step 2 is only relevant if the software contains a Boot Loader allowing the CPU to program the Flash. If the Flash is never being updated by the CPU, step 2 can be omitted. See "Boot Loader Support - Read-While-Write Self-Programming" on page 178 for details about Boot programming. Caution: An interrupt between step 5 and step 6 will make the write cycle fail, since the EEPROM Master Write Enable will time-out. If an interrupt routine accessing the EEPROM is interrupting another EEPROM access, the EEAR or EEDR Register will be modified, causing the interrupted EEPROM access to fail. It is recommended to have the Global Interrupt Flag cleared during all the steps to avoid these problems.
20
ATmega406
2548E-AVR-07/06
ATmega406
When the write access time has elapsed, the EEPE bit is cleared by hardware. The user software can poll this bit and wait for a zero before writing the next byte. When EEPE has been set, the CPU is halted for two cycles before the next instruction is executed. * Bit 0 - EERE: EEPROM Read Enable The EEPROM Read Enable Signal EERE is the read strobe to the EEPROM. When the correct address is set up in the EEAR Register, the EERE bit must be written to a logic one to trigger the EEPROM read. The EEPROM read access takes one instruction, and the requested data is available immediately. When the EEPROM is read, the CPU is halted for four cycles before the next instruction is executed. The user should poll the EEPE bit before starting the read operation. If a write operation is in progress, it is neither possible to read the EEPROM, nor to change the EEAR Register. The calibrated Oscillator is used to time the EEPROM accesses. Table 6-2 lists the typical programming time for EEPROM access from the CPU. Table 6-2.
Symbol EEPROM write (from CPU)
EEPROM Programming Time
Number of Calibrated RC Oscillator Cycles 26,368 Typ Programming Time 3.3 ms
The following code examples show one assembly and one C function for writing to the EEPROM. The examples assume that interrupts are controlled (e.g. by disabling interrupts globally) so that no interrupts will occur during execution of these functions. The examples also assume that no Flash Boot Loader is present in the software. If such code is present, the EEPROM write function must also wait for any ongoing SPM command to finish.
21
2548E-AVR-07/06
Assembly Code Example
EEPROM_write: ; Wait for completion of previous write sbic EECR,EEWE rjmp EEPROM_write ; Set up address (r18:r17) in address register out EEARH, r18 out EEARL, r17 ; Write data (r16) to data register out EEDR,r16 ; Write logical one to EEMWE sbi EECR,EEMWE ; Start eeprom write by setting EEWE sbi EECR,EEWE ret
C Code Example
void EEPROM_write(unsigned int uiAddress, unsigned char ucData) { /* Wait for completion of previous write */ while(EECR & (1<The next code examples show assembly and C functions for reading the EEPROM. The examples assume that interrupts are controlled so that no interrupts will occur during execution of these functions.
22
ATmega406
2548E-AVR-07/06
ATmega406
Assembly Code Example
EEPROM_read: ; Wait for completion of previous write sbic EECR,EEWE rjmp EEPROM_read ; Set up address (r18:r17) in address register out EEARH, r18 out EEARL, r17 ; Start eeprom read by writing EERE sbi EECR,EERE ; Read data from data register in ret r16,EEDR
C Code Example
unsigned char EEPROM_read(unsigned int uiAddress) { /* Wait for completion of previous write */ while(EECR & (1<23
2548E-AVR-07/06
6.4
I/O Memory
The I/O space definition of the ATmega406 is shown in "Register Summary" on page 236. All ATmega406 I/Os and peripherals are placed in the I/O space. All I/O locations may be accessed by the LD/LDS/LDD and ST/STS/STD instructions, transferring data between the 32 general purpose working registers and the I/O space. I/O Registers within the address range 0x00 - 0x1F are directly bit-accessible using the SBI and CBI instructions. In these registers, the value of single bits can be checked by using the SBIS and SBIC instructions. Refer to the instruction set section for more details. When using the I/O specific commands IN and OUT, the I/O addresses 0x00 - 0x3F must be used. When addressing I/O Registers as data space using LD and ST instructions, 0x20 must be added to these addresses. The ATmega406 is a complex microcontroller with more peripheral units than can be supported within the 64 location reserved in Opcode for the IN and OUT instructions. For the Extended I/O space from 0x60 - 0xFF in SRAM, only the ST/STS/STD and LD/LDS/LDD instructions can be used. For compatibility with future devices, reserved bits should be written to zero if accessed. Reserved I/O memory addresses should never be written. Some of the status flags are cleared by writing a logical one to them. Note that, unlike most other AVRs, the CBI and SBI instructions will only operate on the specified bit, and can therefore be used on registers containing such status flags. The CBI and SBI instructions work with registers 0x00 to 0x1F only. The I/O and peripherals control registers are explained in later sections.
6.4.1
General Purpose I/O Registers The ATmega406 contains three General Purpose I/O Registers. These registers can be used for storing any information, and they are particularly useful for storing global variables and Status Flags. General Purpose I/O Registers within the address range 0x00 - 0x1F are directly bitaccessible using the SBI, CBI, SBIS, and SBIC instructions. GPIOR2 - General Purpose I/O Register 2
Bit 0x2B (0x4B) Read/Write Initial Value 7 MSB R/W 0 R/W 0 R/W 0 R/W 0 R/W 0 R/W 0 R/W 0 6 5 4 3 2 1 0 LSB R/W 0 GPIOR2
6.4.2
6.4.3
GPIOR1 - General Purpose I/O Register 1
Bit 0x2A (0x4A) Read/Write Initial Value 7 MSB R/W 0 R/W 0 R/W 0 R/W 0 R/W 0 R/W 0 R/W 0 6 5 4 3 2 1 0 LSB R/W 0 GPIOR1
6.4.4
GPIOR0 - General Purpose I/O Register 0
Bit 0x1E (0x3E) Read/Write Initial Value 7 MSB R/W 0 R/W 0 R/W 0 R/W 0 R/W 0 R/W 0 R/W 0 6 5 4 3 2 1 0 LSB R/W 0 GPIOR0
24
ATmega406
2548E-AVR-07/06
ATmega406
7. System Clock and Clock Options
7.1 Clock Systems and their Distribution
Figure 7-1 presents the principal clock systems in the AVR and their distribution. All of the clocks need not be active at a given time. In order to reduce power consumption, the clocks to modules not being used can be halted by using different sleep modes, as described in "Power Management and Sleep Modes" on page 31. The clock systems are detailed below. Figure 7-1. Clock Distribution
CPU CORE RAM FLASH and EEPROM Voltage ADC Other I/O Modules TWI Coulomb Counter ADC Wake-up Timer
clkFLASH
clkVADC clkCCADC clkWUT
clkCPU
clkI/O
clkTWI
TWI Disconnect Delay
Watchdog Timer
Battery Protection & FET Control
AVR Clock Control
Reset Logic
AVR Clock Control
AVR Clock Control
0
Clock Multiplexer
1
Run-Time Selection
1/4
Sync Delay
1/4
Ultra Low Power RC Oscillator
Fast RC Oscillator
Slow RC Oscillator
32 kHz Crystal Oscillator
7.1.1
CPU Clock - clkCPU The CPU clock is routed to parts of the system concerned with operation of the AVR core. Examples of such modules are the General Purpose Register File, the Status Register and the data memory holding the Stack Pointer. Halting the CPU clock inhibits the core from performing general operations and calculations. TWI Clock - clkTWI The TWI module is provided with a dedicated clock domain. This is because the TWI module requires a 4 MHz clock to achieve the specified Data Transfer Speed. It also allows power reduction by halting the clkTWI clock when TWI communication is not used. Note that address match detection in the TWI module is carried out asynchronously when clkTWI is halted, enabling TWI address watch detection in all sleep modes except Power-off. I/O Clock - clkI/O The I/O clock is used by the majority of the I/O modules. The I/O clock is also used by the External Interrupt module, but note that some external interrupts are detected by asynchronous logic, allowing such interrupts to be detected even if the I/O clock is halted. Flash Clock - clkFLASH The Flash clock controls operation of the Flash interface. The Flash clock is usually active simultaneously with the CPU clock.
7.1.2
7.1.3
7.1.4
25
2548E-AVR-07/06
7.1.5
Voltage ADC Clock - clkVADC The Voltage ADC is provided with a dedicated clock domain. This allows halting the CPU and I/O clocks in order to reduce noise generated by digital circuitry. This gives more accurate ADC conversion results. Coulomb Counter ADC Clock - clkCCADC The Coulomb Counter ADC is provided with a dedicated clock domain. This allows operating the Coulomb Counter ADC in low power modes like Power-save for continuous current measurements. Watchdog Timer and Battery Protection Clock The Watchdog Timer and Battery Protection are provided with a dedicated clock domain. This allows operation in all modes except Power-off. It also allows very low power operation by utilizing an Ultra Low Power RC Oscillator dedicated to this purpose.
7.1.6
7.1.7
7.2
Clock Sources
The device has the following clock sources. The clocks are input to the AVR clock generator, and routed to the appropriate modules.
7.3
Calibrated Fast RC Oscillator
The calibrated Fast RC Oscillator by default provides a 4.0 MHz clock, which is divided down to 1.0 MHz to all modules except the TWI. The frequency is nominal value at 25C. This clock will operate with no external components. During reset, hardware loads the calibration byte into the FOSCCAL Register and thereby automatically calibrates the Fast RC Oscillator. At 25C, this calibration gives a frequency of 4 MHz 3%. The oscillator can be calibrated to any frequency in the range 3.7 - 4.0 MHz within 1% accuracy, by changing the FOSCCAL register. For more information on the pre-programmed calibration value, see the section "Calibration Bytes" on page 198. The start-up times for the Fast RC Oscillator are determined by the SUT Fuses as shown in Table 7-1 on page 26. Table 7-1.
SUT1:0 00 01 10 11 Note: 1. The device is shipped with this option selected.
Start-up times for the internal calibrated RC Oscillator clock selection
Start-up Time from Power-down and Power-save 6 CK 6 CK 6 CK Reserved Additional Delay from Reset 14CK 14CK + 4.1 ms 14CK + 65 ms(1)
26
ATmega406
2548E-AVR-07/06
ATmega406
7.4 32 kHz Crystal Oscillator
XTAL1 and XTAL2 are input and output, respectively, of an inverting amplifier which can be configured for use as an On-chip Oscillator, as shown in Figure 7-2. This Oscillator is optimized for use with a 32.768 kHz watch crystal. C1 and C2 should always be equal. The optimal value of the capacitors depends on the crystal or resonator in use, the amount of stray capacitance, and the electromagnetic noise of the environment. For information on how to choose capacitors and other details on Oscillator operation, refer to the 32 kHz Crystal Oscillator application note. Figure 7-2. 32 kHz Crystal Oscillator Connections
C2 C1
XTAL2 XTAL1 GND
7.5
Slow RC Oscillator
The Slow RC Oscillator provides a fixed 131 kHz clock. This clock source can be used as a backup clock source in case of 32 kHz Crystal Oscillator failure. It can also be used as the only Run-Time clock source in systems where the resulting clock accuracy is acceptable. To provide good accuracy when used as a Run-Time clock source, the slow RC Oscillator has a calibration byte stored in the signature address space. See the section "Calibration Bytes" on page 198. In order to get the actual timeout periods, the application software must use this calibration byte to scale the WUT time-outs found in Table 10-1 on page 50.
7.6
Ultra Low Power RC Oscillator
The Ultra Low Power RC Oscillator (ULP Oscillator) provides a clock of 128 kHz. It operates at very low power consumption, at the expense of frequency accuracy.
7.7
CPU, I/O, Flash, and Voltage ADC Clock
The clock source for the CPU, I/O, Flash, and Voltage ADC is the calibrated Fast RC Oscillator. Note that the Calibrated Fast RC Oscillator will provide a 4 MHz clock to the TWI module and a 1 MHz clock to all other modules. When the CPU wakes up from Power-down or Power-save, the CPU clock source is used to time the start-up, ensuring a stable clock before instruction execution starts. When the CPU starts from reset, there is an additional delay allowing the voltage regulator to reach a stable level before commencing normal operation. The Ultra Low Power RC Oscillator is used for timing this real-time part of the start-up time. Start-up times are determined by the SUT Fuses as
27
2548E-AVR-07/06
shown in Table 7-2. The number of Ultra Low Power RC Oscillator cycles used for each time-out is shown in Table 7-3. Table 7-2.
SUT1:0 00 01 10 11
Start-up Times for the Calibrated Fast RC Oscillator
Start-up Time from Power-down and Power-save 6 CK 6 CK 6 CK Reserved Additional Delay from Reset 14CK 14CK + 3.9 ms 14CK + 62.5 ms
Table 7-3.
Number of Ultra Low Power RC Oscillator Cycles
Typ Time-out 3.9 ms 62.5 ms Number of Cycles 500 8000
7.8
Coulomb Counter ADC and Wake-up Timer Clock
The Coulomb Counter ADC and Wake-up Timer clock operates asynchronously with the CPU clock, to allow low power operation in sleep modes. The clock source is either the 32 kHz Crystal Oscillator, or the Slow RC Oscillator (divided by 4). The selected clock is input to the AVR Clock Control Unit, and is routed to the appropriate modules. The clock source for the Coulomb Counter ADC and Wake-up Timer is selected by an I/O bit in the Clock Control and Status Register, see "Run-Time Clock Source Select" on page 28 for details.
7.9
Watchdog Timer and Battery Protection Clock
The clock source for the Watchdog Timer and Battery Protection is the Ultra Low Power RC Oscillator. The Oscillator is automatically enabled in all operational modes where either the Watchdog Timer, the Battery Protection, or both, are enabled. It is also enabled during reset.
7.10
Run-Time Clock Source Select
The clock source for the Coulomb Counter ADC and Wake-up Timer is run-time selectable as either the 32 kHz Crystal Oscillator, or the Slow RC oscillator (divided by 4). The clock source is selected by an I/O bit in the Clock Control and Status Register. The 32 kHz Crystal Oscillator is the recommended clock source in order to achieve the highest clock accuracy. The Slow RC Oscillator is provided as a clock source for low cost systems, or as an alternate clock source in case of crystal clock failure. If the CPU detects that the crystal clock is not operating correctly, it can switch to the Slow RC Oscillator as a less accurate, but still functional, backup solution.
28
ATmega406
2548E-AVR-07/06
ATmega406
7.11
7.11.1
Register Description
FOSCCAL - Fast RC Oscillator Calibration Register
Bit (0x66) Read/Write Initial Value 7 FCAL7 R/W 6 FCAL6 R/W 5 FCAL5 R/W 4 FCAL4 R/W 3 FCAL3 R/W 2 FCAL2 R/W 1 FCAL1 R/W 0 FCAL0 R/W FOSCCAL
Device Specific Calibration Value
* Bits 7:0 - FCAL7:0: Fast RC Oscillator Calibration Value The Fast RC Oscillator Calibration Register is used to trim the Fast RC Oscillator to remove process variations from the oscillator frequency. The factory-calibrated value is automatically written to this register during chip reset, giving an oscillator frequency of 4.0 MHz at 25C. The application software can write this register to change the oscillator frequency. The oscillator can be calibrated to any frequency in the range 3.7 - 4.0 MHz within 1% accuracy. Calibration outside that range is not guaranteed. Note that this oscillator is used to time EEPROM and Flash write accesses, and these write times will be affected accordingly. If the EEPROM or Flash are written, do not calibrate to more than 4.4 MHz. Otherwise, the EEPROM or Flash write may fail. The FCAL7 bit determines the range of operation for the oscillator. Setting this bit to 0 gives the lowest frequency range, setting this bit to 1 gives the highest frequency range. The two frequency ranges are overlapping, in other words a setting of FOSCCAL = 0x7F gives a higher frequency than FOSCCAL = 0x80. The FCAL6:0 bits are used to tune the frequency within the selected range. A setting of 0x00 gives the lowest frequency in that range, and a setting of 0x7F gives the highest frequency in the range. Incrementing FCAL6:0 by 1 will give a frequency increment of less than 2% in the frequency range 3.7 - 4.0 MHz. 7.11.2 CCSR - Clock Control and Status Register
Bit (0xC0) Read/Write Initial Value 7
-
6
-
5
-
4
-
3
-
2
-
1
XOE
0
ACS CCSR
R 0
R 0
R 0
R 0
R 0
R 0
R/W 0
R/W 0
* Bits 7:2 - Res: Reserved Bits These bits are reserved bits in the ATmega406 and will always read as zero. * Bit 1 - XOE: 32 kHz Crystal Oscillator Enable The XOE bit is used to enable the 32 kHz Crystal Oscillator before it is selected as clock source. This allows the Oscillator clock to stabilize prior to use. The 32 kHz Crystal Oscillator requires approximately two seconds to stabilize, this must be timed by the user software. If the software tries to write a one to ACS and a zero to XOE at the same time, both XOE and ACS will be cleared by the hardware. Thus, while the 32 kHz Crystal Oscillator is disabled it is not possible to select it as a clock source .
29
2548E-AVR-07/06
* Bit 0 - ACS: Asynchronous Clock Select The ACS bit is used to selected the source of the asynchronous clock for the Coulomb Counter ADC and Wake-up Timer. The Slow RC Oscillator is selected when this bit is cleared (zero). The 32 kHz Crystal Oscillator is selected when this bit is set (one). The selected clock source and oscillator enable conditions are illustrated in Table 7-4. Table 7-4.
Sleep Mode Power-off or Power-down Other Sleep Modes Active Mode
Asynchronous Clock Source and Oscillator Enable Conditions
32 kHz Crystal Oscillator Enable 0 XOE XOE Slow RC Oscillator Enable 0 ACS & (CADEN | WUTEN) 1
Recommended algorithm for switching from the RC Oscillator to the Crystal Oscillator as the asynchronous clock for the Coulomb Counter ADC and Wake-up Timer: 1. Enable the Crystal Oscillator by setting the XOE bit (one). 2. Enable the Wake-up Timer, select a two second timeout, and reset the Wake-up Timer ("Wake-up Timer" on page 49 for details). 3. Wait for the Wake-up Timer time-out. 4. Switch to the Crystal Oscillator by setting the ACS bit (one) while keeping the XOE bit set (one). 5. Optional: Wait for another Wake-up Timer time-out, to ensure the Crystal Oscillator is operating correctly. This can be done by enabling another timer interrupt with significantly longer time-out, and checking that the Wake-up Timer time-out occurs first. Recommended algorithm for switching from the Crystal Oscillator to the RC Oscillator as the asynchronous clock for the Coulomb Counter ADC and Wake-up Timer: 1. Switch to the RC Oscillator by clearing the ACS bit (zero) while keeping the XOE bit set (one). 2. Disable the Crystal Oscillator by clearing the XOE bit (zero) while keeping the ACS bit cleared (zero).
30
ATmega406
2548E-AVR-07/06
ATmega406
8. Power Management and Sleep Modes
Sleep modes enable the application to shut down unused modules in the MCU, thereby saving power. The AVR provides various sleep modes allowing the user to tailor the power consumption to the application's requirements. To enter any of the five sleep modes, the SE bit in SMCR must be written to logic one and a SLEEP instruction must be executed. The SM2:0 bits in the SMCR Register select which sleep mode (Idle, ADC Noise Reduction, Power-down, Power-save, or Power-off) will be activated by the SLEEP instruction. See Table 8-1 for a summary. If an enabled interrupt occurs while the MCU is in a sleep mode, the MCU wakes up. The MCU is then halted for four cycles in addition to the start-up time, executes the interrupt routine, and resumes execution from the instruction following SLEEP. The contents of the register file and SRAM are unaltered when the device wakes up from any sleep mode except Power-off. If a reset occurs during sleep mode, the MCU wakes up and executes from the Reset Vector. The MCU will reset when returning from Poweroff mode. Figure 7-1 on page 25 presents the different clock systems in the ATmega406, and their distribution. The figure is helpful in selecting an appropriate sleep mode. 8.0.1 SMCR - Sleep Mode Control Register The Sleep Mode Control Register contains control bits for power management.
Bit 0x33 (0x53) Read/Write Initial Value 7 - R 0 6 - R 0 5 - R 0 4 - R 0 3 SM2 R/W 0 2 SM1 R/W 0 1 SM0 R/W 0 0 SE R/W 0 SMCR
* Bits 7:4 - Res: Reserved Bits These bits are reserved bits in the ATmega406, and will always read as zero. * Bits 3:1 - SM2:0: Sleep Mode Select Bits 2, 1 and 0 These bits select between the five available sleep modes as shown in Table 8-1. Table 8-1.
SM2 0 0 0 0 1 1 1 1 Note:
Sleep Mode Select
SM1 0 0 1 1 0 0 1 1 SM0 0 1 0 1 0 1 0 1 Sleep Mode Idle ADC Noise Reduction Power-down Power-save Power-off(1) Reserved Reserved Reserved
1. SMCR is auto-cleared after 4 cycles when this value is set and the SE bit is written to logic one. To enter this mode, execute SLEEP instruction within 4 cycles after writing SE to logic one.
31
2548E-AVR-07/06
* Bit 0 - SE: Sleep Enable The SE bit must be written to logic one to make the MCU enter the sleep mode when the SLEEP instruction is executed. To avoid the MCU entering the sleep mode unless it is the programmer's purpose, it is recommended to write the Sleep Enable (SE) bit to one just before the execution of the SLEEP instruction and to clear it immediately after waking up.
8.1
Idle Mode
When the SM2:0 bits are written to 000, the SLEEP instruction makes the MCU enter Idle mode, stopping the CPU but allowing all peripheral functions to continue operating. This sleep mode basically halts clkCPU and clkFLASH, while allowing the other clocks to run. Idle mode enables the MCU to wake up from external triggered interrupts as well as internal ones like the Timer Overflow interrupt.
8.2
ADC Noise Reduction Mode
When the SM2:0 bits are written to 001, the SLEEP instruction makes the MCU enter ADC Noise Reduction mode, stopping the CPU but allowing the Voltage ADC (V-ADC), Wake-up Timer (WUT), Watchdog Timer (WDT), Coulomb Counter (CC), Current Battery Protection (CBP), Voltage Battery Protection (VBP), Wake-up on Regular Current (WURC), 32 kHz crystal Oscillator (XOSC_32K) or Slow RC Oscillator (RCOSC_SLOW), the ULTRA Low Power RC Oscillator (RCOSC_ULP), and the Fast RC Oscillator (RCOSC_FAST) to continue operating. This sleep mode basically halts clkI/O, clkCPU, and clkFLASH, while allowing the other clocks to run. This improves the noise environment for the Voltage ADC, enabling higher resolution measurements.
8.3
Power-save Mode
When the SM2:0 bits are written to 011, the SLEEP instruction makes the MCU enter Powersave mode. In this mode, the internal Fast RC Oscillator (RCOSC_FAST) is stopped, while Wake-up Timer (WUT), Watchdog Timer (WDT), Coulomb Counter (CC), Current Battery Protection (CBP), Voltage Battery Protection (VBP), Wake-up on Regular Current (WURC), 32 kHz crystal Oscillator (XOSC_32K) or Slow RC Oscillator (RCOSC_SLOW) and the Ultra Low Power RC Oscillator (RCOSC_ULP) continue operating. This mode will be the default mode when application software does not require operation of CPU, Flash or any of the periphery units running at the Fast internal Oscillator (RCOSC_FAST). If the current through the sense resistor is so small that the Coulomb Counter cannot measure it accurately, Regular Current detection should be enabled to reduce power consumption. The WUT keeps accurately track of the time so that battery self discharge can be calculated. Note that if a level triggered interrupt is used for wake-up from Power-save mode, the changed level must be held for some time to wake up the MCU. Refer to "External Interrupts" on page 56 for details. When waking up from Power-save mode, there is a delay from the wake-up condition occurs until the wake-up becomes effective. This allows the clock to restart and become stable after having been stopped. The wake-up period is defined in "Clock Sources" on page 26.
32
ATmega406
2548E-AVR-07/06
ATmega406
8.4 Power-down Mode
When the SM2:0 bits are written to 010, the SLEEP instruction makes the MCU enter Powerdown mode. In this mode, the Fast RC Oscillator (RCOSC_FAST), 32 kHz Crystal Oscillator (XOSC_32K), and Slow RC Oscillator (RCOSC_SLOW) are stopped, while the the Ultra Low Power RC Oscillator (RCOSC_ULP), External Interrupts, the Battery Protection and the Watchdog continue to operate (if enabled). Note that if a level triggered interrupt is used for wake-up from Power-down mode, the changed level must be held for some time to wake up the MCU. For more details, see "External Interrupts" on page 56. When waking up from Power-down mode, a delay from the wake-up condition occurs until the wake-up becomes effective. This allows the clock to restart and become stable after having been stopped. The wake-up period is defined in "Clock Sources" on page 26.
8.5
Power-off Mode
When the SM2:0 bits are written to 100, the SLEEP instruction makes the CPU ask the voltage regulator to shut off power to the CPU, leaving only the Regulator and the Charger Detect Circuitry to be operational. To ensure that the MCU enters Power-off mode only when intended, the SLEEP instruction must be executed within 4 clock cycles after the SM2..0 bits are written. Note that before entering Power-off sleep mode, interrupts should be disabled by software. Otherwise interrupts may prevent the SLEEP instruction from being executed within the time limit.
Table 8-2.
Active modules in different Sleep Modes
Mode
Module RCOSC_FAST RCOSC_ULP XOSC_32K/ RCOSC_SLOW CPU Flash 8-bit Timer/16-bit Timer SMBus V-ADC CC-ADC External Interrupts CBP(2) VBP WDT
Active X X X X X X X X X X X X X
Idle X X X
ADC NRM X X X
Powersave
Powerdown
Poweroff
X X
X
X X X X X X X X X(1) X X X X X X X X X X X X X X X X(1) X(1)
33
2548E-AVR-07/06
Table 8-2.
Active modules in different Sleep Modes (Continued)
Mode
Module WUT VREG CHARGER_DETECT Note:
Active X X
Idle X X
ADC NRM X X
Powersave X X
Powerdown
Poweroff
X
X X
1. Address Match and Bus Connect/Disconnect Wake-up only. 2. When Discharge-FET is switched off, Short-circuit Protection is automatically disabled to reduce current consumption.
Table 8-3.
Wake-up Sources for Sleep Modes
Wake-up sources
SMBus Address Match and Bus Connect/Disconnect
External Interrupts
Battery Protection Interrupts
Mode Idle ADC NRM Power-save Power-down Power-off
X X X
X X X X
X X X X
X X X X
X X X X
X X X
X X
X X X
X X
X
X
The sleep mode state diagram is shown in Figure 8-1.
34
ATmega406
2548E-AVR-07/06
Charger Connect
Wake-up on Regular Current
SPM/EEPROM Ready
Other I/O
CC-ADC
V-ADC
WDT
WUT
ATmega406
Figure 8-1. Sleep Mode State Diagram
Reset From all States
RESET
Reset Time-out
Interrupt Sleep Sleep Interrupt
Active
Sleep
Interrupt Interrupt Sleep
ADC NRM
Idle
Sleep or Deep Under-voltage
Power-save
Power-down
Deep Under-voltage
Deep Under-voltage
Deep Under-voltage
Deep Under-voltage
Power-off
Charger Connected
Regulator-on
35
2548E-AVR-07/06
8.6
Power Reduction Register
The Power Reduction Register, PRR, provides a method to stop the clock to individual peripherals to reduce power consumption. The current state of the peripheral is frozen and the I/O registers can not be written. Resources used by the peripheral when stopping the clock will remain occupied, hence the peripheral should in most cases be disabled before stopping the clock. Waking up a module, which is done by clearing the bit in PRR, puts the module in the same state as before shutdown. Module shutdown can be used in Idle mode and Active mode to significantly reduce the overall power consumption. In all other sleep modes, the clock is already stopped.
8.6.1
PRR0 - Power Reduction Register 0
Bit (0x64) Read/Write Initial Value 7 - R 0 6 - R 0 5 - R 0 4 - R 0 3 PRTWI R/W 0 2 PRTIM1 R/W 0 1 PRTIM0 R/W 0 0 PRVADC R/W 0 PRR0
* Bit 7:4 - Res: Reserved bits These bits are reserved in ATmega406 and will always read as zero. * Bit 3 - PRTWI: Power Reduction TWI Writing a logic one to this bit shuts down the TWI by stopping the clock to the module. When waking up the TWI again, the TWI should be re initialized to ensure proper operation. * Bit 2 - PRTIM1: Power Reduction Timer/Counter1 Writing a logic one to this bit shuts down the Timer/Counter1 module. When the Timer/Counter1 is enabled, operation will continue like before the shutdown. * Bit 1 - PRTIM0: Power Reduction Timer/Counter0 Writing a logic one to this bit shuts down the Timer/Counter0 module. When the Timer/Counter0 is enabled, operation will continue like before the shutdown. * Bit 0 - PRVADC: Power Reduction V-ADC Writing a logic one to this bit shuts down the V-ADC. The V-ADC must be disabled before shut down.
36
ATmega406
2548E-AVR-07/06
ATmega406
8.7 Minimizing Power Consumption
There are several issues to consider when trying to minimize the power consumption in an AVR controlled system. In general, sleep modes should be used as much as possible, and the sleep mode should be selected so that as few as possible of the device's functions are operating. All functions not needed should be disabled. In particular, the following modules may need special consideration when trying to achieve the lowest possible power consumption. 8.7.1 Watchdog Timer If the Watchdog Timer is not needed in the application, the module should be turned off. If the Watchdog Timer is enabled, it will be enabled in all sleep modes except Power-off. The Watchdog Timer current consumption is significant only in Power-down mode. See "Watchdog Timer" on page 43 for details on how to configure the Watchdog Timer. Port Pins When entering a sleep mode, all port pins should be configured to use minimum power. The most important is then to ensure that no pins drive resistive loads. In sleep modes where both the I/O clock (clkI/O) and the ADC clock (clkADC) are stopped, the input buffers of the device will be disabled. This ensures that no power is consumed by the input logic when not needed. In some cases, the input logic is needed for detecting wake-up conditions, and it will then be enabled. See "Digital Input Enable and Sleep Modes" on page 64 for details on which pins are enabled. If the input buffer is enabled and the input signal is left floating or have an analog signal level close to VREG/2, the input buffer will use excessive power. For analog input pins, the digital input buffer should be disabled at all times. An analog signal level close to VREG/2 on an input pin can cause significant current even in active mode. Digital input buffers can be disabled by writing to the Digital Input Disable Register. Refer to "DIDR0 - Digital Input Disable Register 0" on page 120 for details. 8.7.3 On-chip Debug System If the On-chip debug system is enabled by OCDEN Fuse and the chip enters sleep mode, the main clock source is enabled, and hence, always consumes power. In the deeper sleep modes, this will contribute significantly to the total current consumption. Battery Protection If one of the Battery Protection features is not needed by the application, this feature should be disabled, see "BPCR - Battery Protection Control Register" on page 128. When the Discharge FET is switched off, the Short-Circuit Circuitry will automatically be stopped in order to minimize power consumption. The current consumption in the Battery Protection circuitry is only significant in Power-down mode. Voltage ADC If enabled, the V-ADC will consume power independent of sleep mode. To save power, the VADC should be disabled when not used, and before entering Power-save or Power-down sleep modes. See "Voltage ADC - 10-channel General Purpose 12-bit Sigma-Delta ADC" on page 116 for details on V-ADC operation.
8.7.2
8.7.4
8.7.5
37
2548E-AVR-07/06
8.7.6
Coloumb Counter If enabled, the CC-ADC will consume power independent of sleep mode. To save power, the CC-ADC should be disabled when not used, and before entering Power-down sleep mode. See "Coulomb Counter - Dedicated Fuel Gauging Sigma-delta ADC" on page 106 for details on CCADC operation.
38
ATmega406
2548E-AVR-07/06
ATmega406
9. System Control and Reset
9.1 Resetting the AVR
During reset, all I/O Registers are set to their initial values, and the program starts execution from the Reset Vector. The instruction placed at the Reset Vector must be a JMP - Absolute Jump - instruction to the reset handling routine. If the program never enables an interrupt source, the Interrupt Vectors are not used, and regular program code can be placed at these locations. This is also the case if the Reset Vector is in the Application section while the Interrupt Vectors are in the Boot section or vice versa. The circuit diagram in Figure 9-1 shows the reset logic. The I/O ports of the AVR are immediately reset to their initial state when a reset source goes active. This does not require any clock source to be running. After all reset sources have gone inactive, a delay counter is invoked, stretching the internal reset. This allows the voltage regulator to reach a stable level before normal operation starts. The time-out period of the delay counter is defined by the user through the SUT Fuses. The different selections for the delay period are presented in "Clock Sources" on page 26.
9.2
Reset Sources
The ATmega406 has several reset sources: * Power-on Reset. If the chip is in Power-off mode, the Charger Detect module generates a reset pulse when a charger is connected.See "Power-on Reset and Charger Connect" on page 40 for details. * External Reset. The MCU is reset when a low level is present on the RESET pin for longer than the minimum pulse length. See "External Reset" on page 41 for details. * Watchdog Reset. The MCU is reset when the Watchdog Timer period expires and the Watchdog is enabled. See "Watchdog Reset" on page 42 for details. * Brown-out Reset. The MCU is reset when VREG is below the Brown-out Reset Threshold, VBOT. See "Brown-out Detection" on page 42 for details. * JTAG AVR Reset. The MCU is Reset as long as there is a logic one in the Reset Register, one of the scan chains of the JTAG system. See "JTAG Interface and On-chip Debug System" on page 171 for details.
39
2548E-AVR-07/06
Figure 9-1.
Reset Logic
DATA BUS
MCU Status Register (MCUSR) EXTRF WDRF JTRF BODRF COUNTER RESET Delay Counters PORF Brown-out Detection Power-on Reset Circuit/ Charger Detect VREG Pull-up Resistor RESET
SPIKE FILTER
VREG
BATT
POR
Reset Circuit
JTAG Reset Register
Watchdog Timer
Ultra Low Power RC Oscillator
TIMEOUT
Clock Generator SUT[1:0]
CK
9.2.1
Power-on Reset and Charger Connect To be able to start from power-off, a charger must be detected. In order to detect a charger, the voltage at the BATT pin must rise above the Charger-on Threshold Voltage level,VCOT. This will issue a Power- on Reset (POR), and the chip enters RESET mode. When the Delay Counter times out, the chip will enter Active mode. Table 30-3 on page 230 shows the Power-on Reset characteristics.
40
ATmega406
2548E-AVR-07/06
ATmega406
Figure 9-2. Power-on Reset in Operation.
VCOT VBATT tTOUT POR
TIMEOUT
INTERNAL_RESET
SLEEP_MODE
Power-off
Reset
Active
9.2.2
External Reset An External Reset is generated by a low level on the RESET pin. Reset pulses longer than the minimum pulse width (see Table 30-3 on page 230) will generate a reset, even if the clock is not running. Shorter pulses are not guaranteed to generate a reset. When the applied signal reaches the Reset Threshold Voltage - VRST - on its positive edge, the delay counter starts the MCU after the Time-out period - tTOUT - has expired. Figure 9-3. External Reset During Operation
FET
41
2548E-AVR-07/06
9.2.3
Watchdog Reset When the Watchdog times out, it will generate a short reset pulse of one CK cycle duration. On the falling edge of this pulse, the delay timer starts counting the Time-out period tTOUT. Refer to page 43 for details on operation of the Watchdog Timer. Figure 9-4. Watchdog Reset During Operation
FET
CK
9.2.4
Brown-out Detection ATmega406 has an On-chip Brown-out Detection (BOD) circuit for monitoring the VREG level during operation by comparing it to a fixed trigger level VBOT = 2.7V. The trigger level has a hysteresis to ensure spike free Brown-out Detection. The hysteresis on the detection level should be interpreted as VBOT+ = VBOT + VHYST/2 and VBOT- = VBOT - VHYST/2. The BOD is automatically enabled in all modes of operation, except in Power-off mode. When the BOD is enabled, and VREG decreases to a value below the trigger level (VBOT- in Figure 9-5), the Brown-out Reset is immediately activated. When VCC increases above the trigger level (VBOT+ in Figure 9-5), the delay counter starts the MCU after the Time-out period tTOUT has expired. Figure 9-5. Brown-out Reset During Operation
VREG VBOTVBOT+
RESET
TIME-OUT
tTOUT
INTERNAL RESET
42
ATmega406
2548E-AVR-07/06
ATmega406
9.3 Watchdog Timer
ATmega406 has an Enhanced Watchdog Timer (WDT). The main features are: * Clocked from separate On-chip Oscillator * 3 Operating modes
- Interrupt - System Reset - Interrupt and System Reset * Selectable Time-out period from 16ms to 8s * Possible Hardware fuse Watchdog always on (WDTON) for fail-safe mode
Figure 9-6.
Watchdog Timer
Ultra Low Power RC OSCILLATOR
16ms 32ms 64ms 125ms 250ms 0.5s 1.0s 2.0s 4.0s 8.0s
WATCHDOG RESET WDE
WDP0 WDP1 WDP2 WDP3
MCU RESET
WDIF INTERRUPT
WDIE
The Watchdog Timer (WDT) is a timer counting cycles of the Ultra Low Power RC Oscillator that runs at 128 kHz. The WDT gives an interrupt or a system reset when the counter reaches a given time-out value. In normal operation mode, it is required that the system uses the WDR Watchdog Timer Reset - instruction to restart the counter before the time-out value is reached. If the system doesn't restart the counter, an interrupt or system reset will be issued. In Interrupt mode, the WDT gives an interrupt when the timer expires. This interrupt can be used to wake the device from sleep-modes, and also as a general system timer. One example is to limit the maximum time allowed for certain operations, giving an interrupt when the operation has run longer than expected. In System Reset mode, the WDT gives a reset when the timer expires. This is typically used to prevent system hang-up in case of runaway code. The third mode, Interrupt and System Reset mode, combines the other two modes by first giving an interrupt and then switch to System Reset mode. This mode will for instance allow a safe shutdown by saving critical parameters before a system reset. The Watchdog always on (WDTON) fuse, if programmed, will force the Watchdog Timer to System Reset mode. With the fuse programmed the System Reset mode bit (WDE) and Interrupt mode bit (WDIE) are locked to 1 and 0 respectively. To further ensure program security, alterations to the Watchdog set-up must follow timed sequences. The sequence for clearing WDE and changing time-out configuration is as follows:
43
2548E-AVR-07/06
1. In the same operation, write a logic one to the Watchdog change enable bit (WDCE) and WDE. A logic one must be written to WDE regardless of the previous value of the WDE bit. 2. Within the next four clock cycles, write the WDE and Watchdog prescaler bits (WDP) as desired, but with the WDCE bit cleared. This must be done in one operation. The following code example shows one assembly and one C function for turning off the Watchdog Timer. The example assumes that interrupts are controlled (e.g. by disabling interrupts globally) so that no interrupts will occur during the execution of these functions. Assembly Code Example(1)
WDT_off: ; Turn off global interrupt cli ; Reset Watchdog Timer wdr ; Clear WDRF in MCUSR in andi out r16, MCUSR r16, (0xff & (0<; Write logical one to WDCE and WDE ; Keep old prescaler setting to prevent unintentional time-out in ori out ldi out sei ret r16, WDTCSR r16, (1<; Turn off WDT
; Turn on global interrupt
C Code Example(1)
void WDT_off(void) { __disable_interrupt(); __watchdog_reset(); /* Clear WDRF in MCUSR */ MCUSR &= ~(1<44
ATmega406
2548E-AVR-07/06
ATmega406
Note: If the Watchdog is accidentally enabled, for example by a runaway pointer or brown-out condition, the device will be reset and the Watchdog Timer will stay enabled. If the code is not set up to handle the Watchdog, this might lead to an eternal loop of time-out resets. To avoid this situation, the application software should always clear the Watchdog System Reset Flag (WDRF) and the WDE control bit in the initialisation routine, even if the Watchdog is not in use. The following code example shows one assembly and one C function for changing the time-out value of the Watchdog Timer. Assembly Code Example(1)
WDT_Prescaler_Change: ; Turn off global interrupt cli ; Reset Watchdog Timer wdr ; Start timed sequence in ori out ; -ldi out ; -sei ret r16, WDTCSR r16, (1<; Set new prescaler(time-out) value = 64K cycles (~0.5 s)
; Turn on global interrupt
C Code Example(1)
void WDT_Prescaler_Change(void) { __disable_interrupt(); __watchdog_reset(); /* Start timed equence */ WDTCSR |= (1<Note: The Watchdog Timer should be reset before any change of the WDP bits, since a change in the WDP bits can result in a time-out when switching to a shorter time-out period.
45
2548E-AVR-07/06
9.4
9.4.1
Register Description
MCUSR - MCU Status Register The MCU Status Register provides information on which reset source caused an MCU reset.
Bit 0x34 (0x54) Read/Write Initial Value 7 - R 0 6 - R 0 5 - R 0 4 JTRF R/W 3 WDRF R/W 2 BODRF R/W See Bit Description 1 EXTRF R/W 0 PORF R/W MCUSR
* Bits 7:5 - Res: Reserved Bits These bits are reserved bits in the ATmega406, and will always read as zero. * Bit 4 - JTRF: JTAG Reset Flag This bit is set if a reset is being caused by a logic one in the JTAG Reset Register selected by the JTAG instruction AVR_RESET. This bit is reset by a Power-on Reset, or by writing a logic zero to the flag. * Bit 3 - WDRF: Watchdog Reset Flag This bit is set if a Watchdog Reset occurs. The bit is reset by a Power-on Reset, or by writing a logic zero to the flag. * Bit 2 - BODRF: Brown-out Reset Flag This bit is set if a Brown-out Reset occurs. The bit is reset by a Power-on Reset, or by writing a logic zero to the flag. * Bit 1 - EXTRF: External Reset Flag This bit is set if an External Reset occurs. The bit is reset by a Power-on Reset, or by writing a logic zero to the flag. * Bit 0 - PORF: Power-on Reset Flag This bit is set if a Power-on Reset occurs. The bit is reset only by writing a logic zero to the flag. To make use of the Reset flags to identify a reset condition, the user should read and then reset the MCUSR as early as possible in the program. If the register is cleared before another reset occurs, the source of the reset can be found by examining the reset flags.
46
ATmega406
2548E-AVR-07/06
ATmega406
9.4.2 WDTCSR - Watchdog Timer Control Register
Bit (0x60) Read/Write Initial Value 7 WDIF R/W 0 6 WDIE R/W 0 5 WDP3 R/W 0 4 WDCE R/W 0 3 WDE R/W X 2 WDP2 R/W 0 1 WDP1 R/W 0 0 WDP0 R/W 0 WDTCSR
* Bit 7 - WDIF: Watchdog Interrupt Flag This bit is set when a time-out occurs in the Watchdog Timer and the Watchdog Timer is configured for interrupt. WDIF is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, WDIF is cleared by writing a logic one to the flag. When the I-bit in SREG and WDIE are set, the Watchdog Time-out Interrupt is executed. * Bit 6 - WDIE: Watchdog Interrupt Enable When this bit is written to one and the I-bit in the Status Register is set, the Watchdog Interrupt is enabled. If WDE is cleared in combination with this setting, the Watchdog Timer is in Interrupt Mode, and the corresponding interrupt is executed if time-out in the Watchdog Timer occurs. If WDE is set, the Watchdog Timer is in Interrupt and System Reset Mode. The first time-out in the Watchdog Timer will set WDIF. Executing the corresponding interrupt vector will clear WDIE and WDIF automatically by hardware (the Watchdog goes to System Reset Mode). This is useful for keeping the Watchdog Timer security while using the interrupt. To stay in Interrupt and System Reset Mode, WDIE must be set after each interrupt. This should however not be done within the interrupt service routine itself, as this might compromise the safety-function of the Watchdog System Reset mode. If the interrupt is not executed before the next time-out, a System Reset will be applied. Table 9-1.
WDTON 0 0 0 0 1
Watchdog Timer Configuration
WDE 0 0 1 1 x WDIE 0 1 0 1 x Mode Stopped Interrupt Mode System Reset Mode Interrupt and System Reset Mode System Reset Mode Action on Time-out None Interrupt Reset Interrupt, then go to System Reset Mode Reset
* Bit 5, 2:0 - WDP3:0 : Watchdog Timer Prescaler 3, 2, 1 and 0 The WDP3:0 bits determine the Watchdog Timer prescaling when the Watchdog Timer is enabled. The different prescaling values and their corresponding Timeout Periods are shown in Table 9-2. * Bit 4 - WDCE: Watchdog Change Enable This bit is used in timed sequences for changing WDE and prescaler bits. To clear the WDE bit, and/or change the prescaler bits, WDCE must be set. Once written to one, hardware will clear WDCE after four clock cycles.
47
2548E-AVR-07/06
* Bit 3 - WDE: Watchdog System Reset Enable WDE is overridden by WDRF in MCUSR. This means that WDE is always set when WDRF is set. To clear WDE, WDRF must be cleared first. This feature ensures multiple resets during conditions causing failure, and a safe start-up after the failure. * Bits 5, 2:0 - WDP3:0: Watchdog Timer Prescaler 3, 2, 1, and 0 The WDP3:0 bits determine the Watchdog Timer prescaling when the Watchdog Timer is enabled. The different prescaling values and their corresponding Timeout Periods are shown in Table 9-2.. Table 9-2.
WDP3 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
Watchdog Timer Prescale Select
WDP2 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 WDP1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 WDP0 0 1 0 1 0 1 0 1 0 1 0 1 0 Reserved 1 0 1 Number of WDT Oscillator Cycles 2K cycles 4K cycles 8K cycles 16K cycles 32K cycles 64K cycles 128K cycles 256K cycles 512K cycles 1024K cycles Typical Time-out at VCC = 3.3V 16 ms 32 ms 64 ms 0.125 s 0.25 s 0.5 s 1.0 s 2.0 s 4.0 s 8.0 s
48
ATmega406
2548E-AVR-07/06
ATmega406
10. Wake-up Timer
The following section describes the Wake-up Timer in the ATmega406. * * * *
One Wake-up Timer Interrupt 8 Selectable Time-out Periods Separate Wake-up Timer Calibration Flag Separate Clock Source
10.1
Overview
The Wake-up Timer is clocked either from the Slow RC Oscillator or from the external 32 kHz crystal oscillator. See "Run-Time Clock Source Select" on page 28 for details. By controlling the Wake-up Timer prescaler, the Wake-up interval can be adjusted from 31.25 ms to 4 s. Eight different clock cycle periods can be selected to determine the Time-out period. Figure 10-1. Wake-up Timer
32 kHz OSCILLATOR
clkWUT
WAKE-UP PRESCALER
clkWUT/16K clkWUT/32K clkWUT/64K
1/4
clkWUT/128K
clkWUT/1K
clkWUT/2K
clkWUT/4K
clkWUT/8K
SLOW RC OSCILLATOR
WUTR WUTP0 WUTP1 WUTP2 WUTE
WUTIF
WUTCF
10.2
10.2.1
Register Description
WUTCSR - Wake-up Timer Control and Status Register
Bit (0x62) Read/Write Initial Value 7 WUTIF R/W 0 6 WUTIE R/W 0 5 WUTCF R/W 0 4 WUTR R/W 0 3 WUTE R/W 0 2 WUTP2 R/W 0 1 WUTP1 R/W 0 0 WUTP0 R/W 0 WUTCSR
* Bit 7 - WUTIF: Wake-up Timer Interrupt Flag The WUTIF bit is set (one) when an overflow occurs in the Wake-up Timer. WUTIF is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, WUTIF is cleared by writing a logic one to the flag. When the SREG I-bit, WUTIE (Wake-up Timer Interrupt Enable), and WUTIF are set (one), the Wake-up Timer interrupt is executed.
clkWUT/64
49
2548E-AVR-07/06
* Bit 6 - WUTIE: Wake-up Timer Interrupt Enable When the WUTIE bit and the I-bit in the Status Register are set (one), the Wake-up Timer interrupt is enabled. The corresponding interrupt is executed if a Wake-up Timer overflow occurs, i.e., when the WUTIF bit is set. * Bit 5 - WUTCF: Wake-up Timer Calibration Flag The WUTCF bit is set every 1.95 ms (256 Slow RC OScillator clocks or 64 32 kHz Crystal Oscillator clocks). WUTCF is cleared by writing a logic one to the flag. WUTCF can be used to calibrate the Fast RC Oscillator to the 32 kHz oscillator or the Slow RC Oscillator. * Bit 4 - WUTR: Wake-up Timer Reset When WUTR bit is written to one, the Wake-up Timer is reset, and starts counting from zero. The WUTR bit is always read as zero. * Bit 3 - WUTE: Wake-up Timer Enable When the WUTE bit is set (one) the Wake-up Timer is enabled, and if the WUTE is cleared (zero) the Wake-up Timer function is disabled. It is recommended to reset the Wake-up Timer when enabling it, by simultaneously setting the WUTR and WUTE bits. * Bits 2:0 - WUTP2, WUTP1, WUTP0: Wake-up Timer Prescaler 2, 1, and 0 The WUTP2, WUTP1 and WUTP0 bits determine the Wake-up Timer prescaling when the Wake-up Timer is enabled. The different prescaling values and their corresponding time-out periods are shown in Table 10-1. The Wake-up Timer should always be reset when changing these bits. Table 10-1.
WUTP2 0 0 0 0 1 1 1 1
Wake-up Timer Prescale Select
WUTP1 0 0 1 1 0 0 1 1 WUTP0 0 1 0 1 0 1 0 1 Number of Slow RC Oscillator Cycles 4K(4096) 8K(8192) 16K(16384) 32K(32768) 64K(65536) 128K(131072) 256K(262144) 512K(524288) Number of 32kHz Crystal Oscillator Cycles 1K(1024) 2K(2048) 4K(4096) 8K(8192) 16K(16384) 32K(32768) 64K(65536) 128K(131072) Typical Time-out 31.25 ms 62.5 ms 125 ms 250 ms 0.5 s 1s 2s 4s
50
ATmega406
2548E-AVR-07/06
ATmega406
11. Interrupts
This section describes the specifics of the interrupt handling as performed in ATmega406. For a general explanation of the AVR interrupt handling, refer to "Reset and Interrupt Handling" on page 14.
11.1
Interrupt Vectors in ATmega406
Table 11-1.
Vector No. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 Notes:
Reset and Interrupt Vectors
Program Address(2) 0x0000(1) Source RESET BPINT INT0 INT1 INT2 INT3 PCINT0 PCINT1 WDT WAKE_UP TIMER1 COMP TIMER1 OVF TIMER0 COMPA TIMER0 COMPB TIMER0 OVF TWI BUS C/D TWI VADC CCADC CONV CCADC REG CUR CCADC ACC EE READY SPM READY Interrupt Definition External Pin, Power-on Reset, Brown-out Reset, Watchdog Reset, and JTAG AVR Reset Battery Protection Interrupt External Interrupt Request 0 External Interrupt Request 1 External Interrupt Request 2 External Interrupt Request 3 Pin Change Interrupt 0 Pin Change Interrupt 1 Watchdog Time-out Interrupt Wake-up Timer Overflow Timer 1 Compare Match Timer 1 Overflow Timer 0 Compare Match A Timer 0 Compare Match B Timer 0 Overflow Two-wire Bus Connect/Disconnect Two-wire Serial Interface Voltage ADC Conversion Complete CC-ADC Instantaneous Current Conversion Complete CC-ADC Regular Current CC-ADC Accumulate Current Conversion Complete EEPROM Ready Store Program Memory Ready
0x0002 0x0004 0x0006 0x0008 0x000A 0x000C 0x000E 0x0010 0x0012 0x0014 0x0016 0x0018 0x001A 0x001C 0x001E 0x0020 0x0022 0x0024 0x0026 0x0028 0x002A 0x002C
1. When the BOOTRST Fuse is programmed, the device will jump to the Boot Loader address at reset, see "Boot Loader Support - Read-While-Write Self-Programming" on page 178. 2. When the IVSEL bit in MCUCR is set, Interrupt Vectors will be moved to the start of the Boot Flash Section. The address of each Interrupt Vector will then be the address in this table added to the start address of the Boot Flash Section.
Table 11-2 shows reset and Interrupt Vectors placement for the various combinations of BOOTRST and IVSEL settings. If the program never enables an interrupt source, the Interrupt
51
2548E-AVR-07/06
Vectors are not used, and regular program code can be placed at these locations. This is also the case if the Reset Vector is in the Application section while the Interrupt Vectors are in the Boot section or vice versa. Table 11-2.
BOOTRST 1 1 0 0 Note:
Reset and Interrupt Vectors Placement(1)
IVSEL 0 1 0 1 Reset Address 0x0000 0x0000 Boot Reset Address Boot Reset Address Interrupt Vectors Start Address 0x0002 Boot Reset Address + 0x0002 0x0002 Boot Reset Address + 0x0002
1. The Boot Reset Address is shown in Table 27-7 on page 193. For the BOOTRST Fuse "1" means unprogrammed while "0" means programmed.
The most typical and general program setup for the Reset and Interrupt Vector Addresses in ATmega406 is:
Address 0x0000 0x0002 0x0004 0x0006 0x0008 0x000A 0x000C 0x000E 0x0010 0x0012 0x0014 0x0016 0X0018 0x001A 0x001C 0x001E 0x0020 0x0022 0x0024 0x0026 0x0028 0x002A 0x002C ; 0x002E 0x002F 0x0030 0x0031 0x0032 0x0033 0x0034 ; ... RESET: ldi out ldi out sei ... xxx ... r16, high(RAMEND) SPH,r16 r16, low(RAMEND) SPL,r16 ; Enable interrupts ; Main program start ; Set Stack Pointer to top of RAM Labels Code jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp RESET BPINT EXT_INT0 EXT_INT1 EXT_INT2 EXT_INT3 PCINT0 PCINT1 WDT WAKE_UP TIM1_COMP TIM1_OVF TIM0_COMPA TIM0_COMPB TIM0_OVF TWI_BUS_CD TWI VADC CCADC_CONV CCADC_REC_CUR CCADC_ACC EE_RDY SPM_RDY Comments ; Reset Handler ; Battery Protection Interrupt Handler ; External Interrupt Request 0 Handler ; External Interrupt Request 1 Handler ; External Interrupt Request 2 Handler ; External Interrupt Request 3 Handler ; Pin Change Interrupt 0 Handler ; Pin Change Interrupt 1 Handler ; Watchdog Time-out Interrupt ; Wake-up Timer Overflow ; Timer1 Compare Handler ; Timer1 Overflow Handler ; Timer0 CompareA Handler ; Timer0 CompareB Handler ; Timer0 Overflow Handler ; Two-wire Bus Connect/Disconnect Handler ; Two-wire Serial Interface Handler ; Voltage ADC Conversion Complete Handler ; CC-ADC Instantaneous Current Conversion Complete Handler ; CC-ADC Regular Current Handler ; CC-ADC Accumulate Current Conversion Complete Handler ; EEPROM Ready Handler ; Store Program Memory Ready Handler
52
ATmega406
2548E-AVR-07/06
ATmega406
When the BOOTRST Fuse is unprogrammed, the Boot section size set to 2K bytes and the IVSEL bit in the MCUCR Register is set before any interrupts are enabled, the most typical and general program setup for the Reset and Interrupt Vector Addresses is:
Address Labels 0x0000 0x0001 0x0002 0x0003 0x0004 0x0005 ; .org 0x4C02 0x4C02 0x4C04 ... 0x4C2C jmp jmp ... jmp BPINT EXT_INT0 ... SPM_RDY ; Battery Protection Interrupt Handler ; External Interrupt Request 0 Handler ; ; Store Program Memory Ready Handler RESET: Code ldi out ldi out sei SPH,r16 r16,low(RAMEND) SPL,r16 ; Enable interrupts xxx Comments r16,high(RAMEND); Main program start ; Set Stack Pointer to top of RAM
When the BOOTRST Fuse is programmed and the Boot section size set to 2K bytes, the most typical and general program setup for the Reset and Interrupt Vector Addresses is:
Address Labels .org 0x0002 0x0002 0x0004 ... 0x002C ; .org 0x4C00 0x4C00 RESET: 0x4C01 0x4C02 0x4C03 0x4C04 0x4C05 ldi out ldi out sei r16,high(RAMEND); Main program start SPH,r16 r16,low(RAMEND) SPL,r16 ; Enable interrupts xxx ; Set Stack Pointer to top of RAM jmp jmp jmp ... BPINT EXT_INT0 ... SPM_RDY ; Battery Protection Interrupt Handler ; External Interrupt Request 0 Handler ; ; Store Program Memory Ready Handler Code Comments
When the BOOTRST Fuse is programmed, the Boot section size set to 2K bytes and the IVSEL bit in the MCUCR Register is set before any interrupts are enabled, the most typical and general program setup for the Reset and Interrupt Vector Addresses is:
Address Labels Code ; .org 0x4C00 0x4C00 0x4C02 0x4C04 ... 0x4C2C ; 0x4C2E RESET: ldi r16,high(RAMEND); Main program start jmp jmp jmp ... jmp RESET BPINT EXT_INT0 ... SPM_RDY ; Reset handler ; Battery Protection Interrupt Handler ; External Interrupt Request 0 Handler ; ; Store Program Memory Ready Handler Comments
53
2548E-AVR-07/06
0x4C2F 0x4C30 0x4C31 0x4C32 0x4C33
out ldi out sei
SPH,r16 r16,low(RAMEND) SPL,r16
; Set Stack Pointer to top of RAM
; Enable interrupts xxx
11.2
Moving Interrupts Between Application and Boot Space
The General Interrupt Control Register controls the placement of the Interrupt Vector table.
Assembly Code Example
Move_interrupts: ; Enable change of Interrupt Vectors ldi r16, (1<C Code Example
void Move_interrupts(void) { /* Enable change of Interrupt Vectors */ MCUCR = (1<54
ATmega406
2548E-AVR-07/06
ATmega406
11.3
11.3.1
Register Description
MCUCR - MCU Control Register
Bit 0x35 (0x55) Read/Write Initial Value 7 JTD R/W 0 6 - R 0 5 - R 0 4 PUD R/W 0 3 - R 0 2 - R 0 1 IVSEL R/W 0 0 IVCE R/W 0 MCUCR
* Bit 1 - IVSEL: Interrupt Vector Select When the IVSEL bit is cleared (zero), the Interrupt Vectors are placed at the start of the Flash memory. When this bit is set (one), the Interrupt Vectors are moved to the beginning of the Boot Loader section of the Flash. The actual address of the start of the Boot Flash Section is determined by the BOOTSZ Fuses. Refer to the section "Boot Loader Support - Read-While-Write Self-Programming" on page 178 for details. To avoid unintentional changes of Interrupt Vector tables, a special write procedure must be followed to change the IVSEL bit: a. Write the Interrupt Vector Change Enable (IVCE) bit to one. b. Within four cycles, write the desired value to IVSEL while writing a zero to IVCE.
Interrupts will automatically be disabled while this sequence is executed. Interrupts are disabled in the cycle IVCE is set, and they remain disabled until after the instruction following the write to IVSEL. If IVSEL is not written, interrupts remain disabled for four cycles. The I-bit in the Status Register is unaffected by the automatic disabling.
Note: If Interrupt Vectors are placed in the Boot Loader section and Boot Lock bit BLB02 is programmed, interrupts are disabled while executing from the Application section. If Interrupt Vectors are placed in the Application section and Boot Lock bit BLB12 is programed, interrupts are disabled while executing from the Boot Loader section. Refer to the section "Boot Loader Support - Read-WhileWrite Self-Programming" on page 178 for details on Boot Lock bits.
* Bit 0 - IVCE: Interrupt Vector Change Enable The IVCE bit must be written to logic one to enable change of the IVSEL bit. IVCE is cleared by hardware four cycles after it is written or when IVSEL is written. Setting the IVCE bit will disable interrupts, as explained in the IVSEL description above. See Code Example below.
55
2548E-AVR-07/06
12. External Interrupts
12.1 Overview
The External Interrupts are triggered by the INT3:0 pins. Observe that, if enabled, the interrupts will trigger even if the INT3:0 pins are configured as outputs. This feature provides a way of generating a software interrupt. The External Interrupts can be triggered by a falling or rising edge or a low level. This is set up as indicated in the specification for the External Interrupt Control Register - EICRA. When the external interrupt is enabled and is configured as level triggered, the interrupt will trigger as long as the pin is held low. Interrupts are detected asynchronously. This implies that these interrupts can be used for waking the part also from sleep modes other than Idle mode. The I/O clock is halted in all sleep modes except Idle mode. Note that if a level triggered interrupt is used for wake-up from Power-down mode, the changed level must be held for some time to wake up the MCU. This makes the MCU less sensitive to noise. The changed level is sampled twice by the Slow RC Oscillator clock. The period of the Slow RC Oscillator is 7.8 s (nominal) at 25C. The MCU will wake up if the input has the required level during this sampling or if it is held until the end of the start-up time. The start-up time is defined by the SUT fuses as described in "System Clock and Clock Options" on page 25. If the level is sampled twice by the Slow RC Oscillator clock but disappears before the end of the start-up time, the MCU will still wake up, but no interrupt will be generated. The required level must be held long enough for the MCU to complete the wake up to trigger the level interrupt.
12.2
12.2.1
Register Description
EICRA - External Interrupt Control Register A
Bit (0x69) Read/Write Initial Value 7 ISC31 R/W 0 6 ISC30 R/W 0 5 ISC21 R/W 0 4 ISC20 R/W 0 3 ISC11 R/W 0 2 ISC10 R/W 0 1 ISC01 R/W 0 0 ISC00 R/W 0 EICRA
* Bits 7:0 - ISC31, ISC30 - ISC01, ISC00: External Interrupt 3 - 0 Sense Control Bits The External Interrupts 3 - 0 are activated by the external pins INT3:0 if the SREG I-flag and the corresponding interrupt mask in the EIMSK is set. The level and edges on the external pins that activate the interrupts are defined in Table 12-1 on page 57. Edges on INT3:INT0 are registered asynchronously. Pulses on INT3:0 pins wider than the minimum pulse width given in Table 12-2 on page 57 will generate an interrupt. Shorter pulses are not guaranteed to generate an interrupt. If low level interrupt is selected, the low level must be held until the completion of the currently executing instruction to generate an interrupt. If enabled, a level triggered interrupt will generate an interrupt request as long as the pin is held low. When changing the ISCn bit, an interrupt can occur. Therefore, it is recommended to first disable INTn by clearing its Interrupt Enable bit in the EIMSK Register. Then, the ISCn bit can be changed. Finally, the INTn interrupt flag should be cleared by writing a logical one to its Interrupt Flag bit (INTFn) in the EIFR Register before the interrupt is re-enabled.
56
ATmega406
2548E-AVR-07/06
ATmega406
Table 12-1.
ISCn1 0 0 1 1 Note:
Interrupt Sense Control
ISCn0 0 1 0 1 Description(1) The low level of INTn generates an interrupt request. Any logical change on INTn generates an interrupt request. The falling edge of INTn generates an interrupt request. The rising edge of INTn generates an interrupt request.
1. n = 3, 2, 1, or 0. When changing the ISCn1/ISCn0 bits, the interrupt must be disabled by clearing its Interrupt Enable bit in the EIMSK Register. Otherwise an interrupt can occur when the bits are changed.
Table 12-2.
Symbol tINT
Asynchronous External Interrupt Characteristics
Parameter Minimum pulse width for asynchronous external interrupt Condition Min Typ 50 Max Units ns
12.2.2
EIMSK - External Interrupt Mask Register
Bit 0x1D (0x3D) Read/Write Initial Value 7 - R 0 6 - R 0 5 - R 0 4 - R 0 3 INT3 R/W 0 2 INT2 R/W 0 1 INT1 R/W 0 0 INT0 R/W 0 EIMSK
* Bits 7:4 - RES: Reserved Bits These bits are reserved bits ins the ATmega406, and will always read as zero. * Bits 3:0 - INT3 - INT0: External Interrupt Request 3 - 0 Enable When an INT3 - INT0 bit is written to one and the I-bit in the Status Register (SREG) is set (one), the corresponding external pin interrupt is enabled. The Interrupt Sense Control bits in the External Interrupt Control Register - EICRA - defines whether the external interrupt is activated on rising or falling edge or level sensed. Activity on any of these pins will trigger an interrupt request even if the pin is enabled as an output. This provides a way of generating a software interrupt. 12.2.3 EIFR - External Interrupt Flag Register
Bit 0x1C (0x3C) Read/Write Initial Value 7 - R 0 6 - R 0 5 - R 0 4 - R 0 3 INTF3 R/W 0 2 INTF2 R/W 0 1 INTF1 R/W 0 0 INTF0 R/W 0 EIFR
* Bits 7:4 - RES: Reserved Bits These bits are reserved bits ins the ATmega406, and will always read as zero. * Bits 3:0 - INTF3 - INTF0: External Interrupt Flags 3 - 0 When an edge or logic change on the INT3:0 pin triggers an interrupt request, INTF3:0 becomes set (one). If the I-bit in SREG and the corresponding interrupt enable bit, INT3:0 in EIMSK, are
57
2548E-AVR-07/06
set (one), the MCU will jump to the interrupt vector. The flag is cleared when the interrupt routine is executed. Alternatively, the flag can be cleared by writing a logical one to it. These flags are always cleared when INT3:0 are configured as level interrupt. Note that when entering sleep mode with the INT3:0 interrupts disabled, the input buffers on these pins will be disabled. This may cause a logic change in internal signals which will set the INTF3:0 flags. See "Digital Input Enable and Sleep Modes" on page 64 for more information. 12.2.4 PCICR- Pin Change Interrupt Control Register
Bit (0x68) Read/Write Initial Value 7 - R 0 6 - R 0 5 - R 0 4 - R 0 3 - R 0 2 - R 0 1 PCIE1 R/W 0 0 PCIE0 R/W 0 PCICR
* Bit 7:2 - Res: Reserved Bits These bits are reserved bits in the ATmega406, and will always read as zero. * Bit 1 - PCIE1: Pin Change Interrupt Enable 1 When the PCIE1 bit is set (one) and the I-bit in the Status Register (SREG) is set (one), pin change interrupt 1 is enabled. Any change on any enabled PCINT15:8 pin will cause an interrupt. The corresponding interrupt of Pin Change Interrupt Request is executed from the PCI1 Interrupt Vector. PCINT15:8 pins are enabled individually by the PCMSK1 Register. * Bit 0 - PCIE0: Pin Change Interrupt Enable 0 When the PCIE0 bit is set (one) and the I-bit in the Status Register (SREG) is set (one), pin change interrupt 0 is enabled. Any change on any enabled PCINT7:0 pin will cause an interrupt. The corresponding interrupt of Pin Change Interrupt Request is executed from the PCI0 Interrupt Vector. PCINT7:0 pins are enabled individually by the PCMSK0 Register. 12.2.5 PCIFR - Pin Change Interrupt Flag Register
Bit 0x1B (0x3B) Read/Write Initial Value 7 - R 0 6 - R 0 5 - R 0 4 - R 0 3 - R 0 2 - R 0 1 PCIF1 R/W 0 0 PCIF0 R/W 0 PCIFR
* Bit 7:2 - Res: Reserved Bits These bits are reserved bits in the ATmega406, and will always read as zero. * Bit 1 - PCIF1: Pin Change Interrupt Flag 1 When a logic change on any PCINT15:8 pin triggers an interrupt request, PCIF1 becomes set (one). If the I-bit in SREG and the PCIE1 bit in PCICR are set (one), the MCU will jump to the corresponding Interrupt Vector. The flag is cleared when the interrupt routine is executed. Alternatively, the flag can be cleared by writing a logical one to it. * Bit 0 - PCIF0: Pin Change Interrupt Flag 0 When a logic change on any PCINT7:0 pin triggers an interrupt request, PCIF0 becomes set (one). If the I-bit in SREG and the PCIE0 bit in PCICR are set (one), the MCU will jump to the
58
ATmega406
2548E-AVR-07/06
ATmega406
corresponding Interrupt Vector. The flag is cleared when the interrupt routine is executed. Alternatively, the flag can be cleared by writing a logical one to it. 12.2.6 PCMSK1 - Pin Change Mask Register 1
Bit (0x6C) Read/Write Initial Value 7
PCINT15
6
PCINT14
5
PCINT13
4
PCINT12
3
PCINT11
2
PCINT10
1
PCINT9
0
PCINT8 PCMSK1
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
* Bit 7:0 - PCINT15:8: Pin Change Enable Mask 15:8 Each PCINT15:8-bit selects whether pin change interrupt is enabled on the corresponding I/O pin. If PCINT15:8 is set and the PCIE1 bit in PCICR is set, pin change interrupt is enabled on the corresponding I/O pin. If PCINT15:8 is cleared, pin change interrupt on the corresponding I/O pin is disabled. 12.2.7 PCMSK0 - Pin Change Mask Register 0
Bit (0x6B) Read/Write Initial Value 7 PCINT7 R/W 0 6 PCINT6 R/W 0 5 PCINT5 R/W 0 4 PCINT4 R/W 0 3 PCINT3 R/W 0 2 PCINT2 R/W 0 1 PCINT1 R/W 0 0 PCINT0 R/W 0 PCMSK0
* Bit 7:0 - PCINT7:0: Pin Change Enable Mask 7:0 Each PCINT7:0 bit selects whether pin change interrupt is enabled on the corresponding I/O pin. If PCINT7:0 is set and the PCIE0 bit in PCICR is set, pin change interrupt is enabled on the corresponding I/O pin. If PCINT7:0 is cleared, pin change interrupt on the corresponding I/O pin is disabled.
59
2548E-AVR-07/06
13. Low Voltage I/O-Ports
13.1 Introduction
All low voltage AVR ports have true Read-Modify-Write functionality when used as general digital I/O ports. This means that the direction of one port pin can be changed without unintentionally changing the direction of any other pin with the SBI and CBI instructions. The same applies when changing drive value (if configured as output) or enabling/disabling of pull-up resistors (if configured as input). All low voltage port pins have individually selectable pull-up resistors with a supply-voltage invariant resistance. All I/O pins have protection diodes to both VREG and Ground as indicated in Figure 13-1 on page 60. Refer to "Electrical Characteristics" on page 225 for a complete list of parameters. Figure 13-1. Low Voltage I/O Pin Equivalent Schematic
Rpu
Pxn
Logic Cpin
See Figure "General Digital I/O" for Details
All registers and bit references in this section are written in general form. A lower case "x" represents the numbering letter for the port, and a lower case "n" represents the bit number. However, when using the register or bit defines in a program, the precise form must be used. For example, PORTB3 for bit no. 3 in Port B, here documented generally as PORTxn. The physical I/O Registers and bit locations are listed in "Register Description" on page 73. Three I/O memory address locations are allocated for each low voltage port, one each for the Data Register - PORTx, Data Direction Register - DDRx, and the Port Input Pins - PINx. The Port Input Pins I/O location is read only, while the Data Register and the Data Direction Register are read/write. However, writing a logic one to a bit in the PINx Register, will result in a toggle in the corresponding bit in the Data Register. In addition, the Pull-up Disable - PUD bit in MCUCR disables the pull-up function for all low voltage pins in all ports when set. Using the I/O port as General Digital I/O is described in "Low Voltage Ports as General Digital I/O" on page 61. Many low voltage port pins are multiplexed with alternate functions for the peripheral features on the device. How each alternate function interferes with the port pin is described in "Alternate Port Functions" on page 66. Refer to the individual module sections for a full description of the alternate functions. Note that enabling the alternate function of some of the port pins does not affect the use of the other pins in the port as general digital I/O.
60
ATmega406
2548E-AVR-07/06
ATmega406
13.2 Low Voltage Ports as General Digital I/O
The low voltage ports are bi-directional I/O ports with optional internal pull-ups. Figure 13-2 shows a functional description of one I/O-port pin, here generically called Pxn. Figure 13-2. General Low Voltage Digital I/O(1)
PUD
Q
D
DDxn Q CLR
RESET
WDx RDx
1 Pxn
Q D PORTxn Q CLR
0
WPx RESET WRx SLEEP RRx
SYNCHRONIZER
D Q D Q
RPx
PINxn L Q Q
clk I/O
PUD: SLEEP: clkI/O:
PULLUP DISABLE SLEEP CONTROL I/O CLOCK
WDx: RDx: WRx: RRx: RPx: WPx:
WRITE DDRx READ DDRx WRITE PORTx READ PORTx REGISTER READ PORTx PIN WRITE PINx REGISTER
Note:
1. WRx, WPx, WDx, RRx, RPx, and RDx are common to all pins within the same port. clkI/O, SLEEP, and PUD are common to all ports.
13.2.1
Configuring the Pin Each port pin consists of three register bits: DDxn, PORTxn, and PINxn. As shown in "Register Description" on page 73, the DDxn bits are accessed at the DDRx I/O address, the PORTxn bits at the PORTx I/O address, and the PINxn bits at the PINx I/O address. The DDxn bit in the DDRx Register selects the direction of this pin. If DDxn is written logic one, Pxn is configured as an output pin. If DDxn is written logic zero, Pxn is configured as an input pin. If PORTxn is written logic one when the pin is configured as an input pin, the pull-up resistor is activated. To switch the pull-up resistor off, PORTxn has to be written logic zero or the pin has to be configured as an output pin. The port pins are tri-stated when reset condition becomes active, even if no clocks are running. If PORTxn is written logic one when the pin is configured as an output pin, the port pin is driven high (one). If PORTxn is written logic zero when the pin is configured as an output pin, the port pin is driven low (zero).
DATA BUS
61
2548E-AVR-07/06
13.2.2
Toggling the Pin Writing a logic one to PINxn toggles the value of PORTxn, independent on the value of DDRxn. Note that the SBI instruction can be used to toggle one single bit in a port. Switching Between Input and Output When switching between tri-state ({DDxn, PORTxn} = 0b00) and output high ({DDxn, PORTxn} = 0b11), an intermediate state with either pull-up enabled {DDxn, PORTxn} = 0b01) or output low ({DDxn, PORTxn} = 0b10) must occur. Normally, the pull-up enabled state is fully acceptable, as a high-impedant environment will not notice the difference between a strong high driver and a pull-up. If this is not the case, the PUD bit in the MCUCR Register can be set to disable all pull-ups in all ports. Switching between input with pull-up and output low generates the same problem. The user must use either the tri-state ({DDxn, PORTxn} = 0b00) or the output high state ({DDxn, PORTxn} = 0b11) as an intermediate step. Table 13-1 summarizes the control signals for the pin value. Table 13-1.
DDxn 0 0 0 1 1
13.2.3
Port Pin Configurations
PUD (in MCUCR) X 0 1 X X I/O Input Input Input Output Output Pull-up No Yes No No No Comment Tri-state (Hi-Z) Pxn will source current if ext. pulled low. Tri-state (Hi-Z) Output Low (Sink) Output High (Source)
PORTxn 0 1 1 0 1
13.2.4
Reading the Pin Value Independent of the setting of Data Direction bit DDxn, the port pin can be read through the PINxn Register bit. As shown in Figure 13-2, the PINxn Register bit and the preceding latch constitute a synchronizer. This is needed to avoid metastability if the physical pin changes value near the edge of the internal clock, but it also introduces a delay. Figure 13-3 shows a timing diagram of the synchronization when reading an externally applied pin value. The maximum and minimum propagation delays are denoted tpd,max and tpd,min respectively.
62
ATmega406
2548E-AVR-07/06
ATmega406
Figure 13-3. Synchronization when Reading an Externally Applied Pin value
SYSTEM CLK INSTRUCTIONS SYNC LATCH PINxn r17
0x00 t pd, max t pd, min 0xFF XXX XXX in r17, PINx
Consider the clock period starting shortly after the first falling edge of the system clock. The latch is closed when the clock is low, and goes transparent when the clock is high, as indicated by the shaded region of the "SYNC LATCH" signal. The signal value is latched when the system clock goes low. It is clocked into the PINxn Register at the succeeding positive clock edge. As indicated by the two arrows tpd,max and tpd,min, a single signal transition on the pin will be delayed between 1/2 and 11/2 system clock period depending upon the time of assertion. When reading back a software assigned pin value, a nop instruction must be inserted as indicated in Figure 13-4. The out instruction sets the "SYNC LATCH" signal at the positive edge of the clock. In this case, the delay tpd through the synchronizer is 1 system clock period. Figure 13-4. Synchronization when Reading a Software Assigned Pin Value
SYSTEM CLK r16 INSTRUCTIONS SYNC LATCH PINxn r17
0x00 t pd 0xFF out PORTx, r16 nop 0xFF
in r17, PINx
The following code example shows how to set port B pins 0 and 1 high, 2 and 3 low, and define the port pins from 4 to 7 as input with pull-ups assigned to port pins 6 and 7. The resulting pin values are read back again, but as previously discussed, a nop instruction is included to be able to read back the value recently assigned to some of the pins. 63
2548E-AVR-07/06
Assembly Code Example(1)
... ; Define pull-ups and set outputs high ; Define directions for port pins ldi ldi out out nop ; Read port pins in ... r16,PINB r16,(1<; Insert nop for synchronization
C Code Example
unsigned char i; ... /* Define pull-ups and set outputs high */ /* Define directions for port pins */ PORTB = (1<13.2.5
Digital Input Enable and Sleep Modes As shown in Figure 13-2, the digital input signal can be clamped to ground at the input of the schmitt-trigger. The signal denoted SLEEP in the figure, is set by the MCU Sleep Controller in Power-down mode and Power-save mode to avoid high power consumption if some input signals are left floating, or have an analog signal level close to VREG/2. SLEEP is overridden for port pins enabled as external interrupt pins. If the external interrupt request is not enabled, SLEEP is active also for these pins. SLEEP is also overridden by various other alternate functions as described in "Alternate Port Functions" on page 66. If a logic high level ("one") is present on an asynchronous external interrupt pin configured as "Interrupt on Rising Edge, Falling Edge, or Any Logic Change on Pin" while the external interrupt is not enabled, the corresponding External Interrupt Flag will be set when resuming from the above mentioned Sleep mode, as the clamping in these sleep mode produces the requested logic change.
64
ATmega406
2548E-AVR-07/06
ATmega406
13.2.6 Unconnected Pins If some pins are unused, it is recommended to ensure that these pins have a defined level. Even though most of the digital inputs are disabled in the deep sleep modes as described above, floating inputs should be avoided to reduce current consumption in all other modes where the digital inputs are enabled (Reset, Active mode and Idle mode). The simplest method to ensure a defined level of an unused pin, is to enable the internal pull-up. In this case, the pull-up will be disabled during reset. If low power consumption during reset is important, it is recommended to use an external pull-up or pull-down. Connecting unused pins directly to VCC or GND is not recommended, since this may cause excessive currents if the pin is accidentally configured as an output.
65
2548E-AVR-07/06
13.3
Alternate Port Functions
Many low voltage port pins have alternate functions in addition to being general digital I/Os. Figure 13-5 shows how the port pin control signals from the simplified Figure 13-2 can be overridden by alternate functions. The overriding signals may not be present in all port pins, but the figure serves as a generic description applicable to all port pins in the AVR microcontroller family. Figure 13-5. Alternate Port Functions(1)
PUOExn PUOVxn
1 0
PUD
DDOExn DDOVxn
1 0
D Q DDxn Q CLR
PVOExn PVOVxn
WDx RESET RDx
1 Pxn 0
Q D
1 0
PORTxn
DIEOExn DIEOVxn
1 0
Q CLR
PTOExn WPx
RESET RRx
WRx
SLEEP SYNCHRONIZER
D
SET
RPx
Q
D
Q
PINxn L
CLR
Q
CLR
Q
clk I/O
DIxn
AIOxn
PUOExn: PUOVxn: DDOExn: DDOVxn: PVOExn: PVOVxn: DIEOExn: DIEOVxn: SLEEP: PTOExn:
Pxn PULL-UP OVERRIDE ENABLE Pxn PULL-UP OVERRIDE VALUE Pxn DATA DIRECTION OVERRIDE ENABLE Pxn DATA DIRECTION OVERRIDE VALUE Pxn PORT VALUE OVERRIDE ENABLE Pxn PORT VALUE OVERRIDE VALUE Pxn DIGITAL INPUT-ENABLE OVERRIDE ENABLE Pxn DIGITAL INPUT-ENABLE OVERRIDE VALUE SLEEP CONTROL Pxn, PORT TOGGLE OVERRIDE ENABLE
PUD: WDx: RDx: RRx: WRx: RPx: WPx: clkI/O: DIxn: AIOxn:
PULLUP DISABLE WRITE DDRx READ DDRx READ PORTx REGISTER WRITE PORTx READ PORTx PIN WRITE PINx I/O CLOCK DIGITAL INPUT PIN n ON PORTx ANALOG INPUT/OUTPUT PIN n ON PORTx
Note:
1. WRx, WPx, WDx, RRx, RPx, and RDx are common to all pins within the same port. clkI/O, SLEEP, and PUD are common to all ports. All other signals are unique for each pin.
66
ATmega406
2548E-AVR-07/06
DATA BUS
ATmega406
Table 13-2 summarizes the function of the overriding signals. The pin and port indexes from Figure 13-5 are not shown in the succeeding tables. The overriding signals are generated internally in the modules having the alternate function. Table 13-2.
Signal Name PUOE
Generic Description of Overriding Signals for Alternate Functions
Full Name Pull-up Override Enable Pull-up Override Value Data Direction Override Enable Data Direction Override Value Description If this signal is set, the pull-up enable is controlled by the PUOV signal. If this signal is cleared, the pull-up is enabled when {DDxn, PORTxn, PUD} = 0b010. If PUOE is set, the pull-up is enabled/disabled when PUOV is set/cleared, regardless of the setting of the DDxn, PORTxn, and PUD Register bits. If this signal is set, the Output Driver Enable is controlled by the DDOV signal. If this signal is cleared, the Output driver is enabled by the DDxn Register bit. If DDOE is set, the Output Driver is enabled/disabled when DDOV is set/cleared, regardless of the setting of the DDxn Register bit. If this signal is set and the Output Driver is enabled, the port value is controlled by the PVOV signal. If PVOE is cleared, and the Output Driver is enabled, the port Value is controlled by the PORTxn Register bit. If PVOE is set, the port value is set to PVOV, regardless of the setting of the PORTxn Register bit. If PTOE is set, the PORTxn Register bit is inverted. If this bit is set, the Digital Input Enable is controlled by the DIEOV signal. If this signal is cleared, the Digital Input Enable is determined by MCU state (Normal mode, sleep mode). If DIEOE is set, the Digital Input is enabled/disabled when DIEOV is set/cleared, regardless of the MCU state (Normal mode, sleep mode). This is the Digital Input to alternate functions. In the figure, the signal is connected to the output of the schmitt trigger but before the synchronizer. Unless the Digital Input is used as a clock source, the module with the alternate function will use its own synchronizer. This is the Analog Input/output to/from alternate functions. The signal is connected directly to the pad, and can be used bidirectionally.
PUOV
DDOE
DDOV
PVOE
Port Value Override Enable Port Value Override Value Port Toggle Override Enable Digital Input Enable Override Enable Digital Input Enable Override Value
PVOV PTOE
DIEOE
DIEOV
DI
Digital Input
AIO
Analog Input/Output
The following subsections shortly describe the alternate functions for each port, and relate the overriding signals to the alternate function. Refer to the alternate function description for further details.
67
2548E-AVR-07/06
13.3.1
Alternate Functions of Port A The Port A has an alternate function as input pins to the Voltage ADC. Table 13-3. Port A Pins Alternate Functions
Alternate Function INT3 (External Interrupt 3) PCINT7 (Pin Change Interrupt 7) INT2 (External Interrupt 2) PCINT6 (Pin Change Interrupt 6) INT1 (External Interrupt 1) PCINT5 (Pin Change Interrupt 5) ADC4 (ADC Input Channel 4) INT0 (External Interrupt 0) PCINT4 (Pin Change Interrupt 4) ADC3 (ADC Input Channel 3) PCINT3 (Pin Change Interrupt 3) ADC2 (ADC Input Channel 2) PCINT2 (Pin Change Interrupt 2) ADC1 (ADC Input Channel 1) PCINT1 (Pin Change Interrupt 1) ADC0 (ADC Input Channel 0) PCINT0 (Pin Change Interrupt 0)
Port Pin PA7 PA6 PA5
PA4
PA3 PA2 PA1 PA0
The alternate pin configuration is as follows: * ADC4/INT3:0/PCINT7:4 - Port A, Bit 7:4 Analog to Digital Converter, Channel 4. INT3 - INT0, External Interrupt Sources 3:0. The PA7:4 pins can serve as external interrupt sources to the MCU. PCINT7 - PCINT4, Pin Change Interrupt Sources 7:4. The PA7:4 pins can serve as external interrupt sources to the MCU. * ADC3:0/PCINT3:0 - Port A, Bit 3:0 Analog to Digital Converter, Channels 3:0. PCINT3 - PCINT0, Pin Change Interrupt Sources 3:0. The PA3:0 pins can serve as external interrupt sources to the MCU.
68
ATmega406
2548E-AVR-07/06
ATmega406
Table 13-4 and Table 13-5 relates the alternate functions of Port A to the overriding signals shown in Figure 13-5 on page 66. Table 13-4.
Signal Name PUOE PUOV DDOE DDOV PVOE PVOV PTOE DIEOE DIEOV DI AIO
Overriding Signals for Alternate Functions in PA7:PA4
PA7/INT3/ PCINT7 0 0 0 0 0 0 - INT3 ENABLE INT3 ENABLE INT3 INPUT/ PCINT7 INPUT - PA6/INT2/ PCINT6 0 0 0 0 0 0 - INT2 ENABLE INT2 ENABLE INT2 INPUT/ PCINT6 INPUT - PA5/INT1/ PCINT5 0 0 0 0 0 0 - INT1 ENABLE INT1 ENABLE INT1 INPUT/ PCINT5 INPUT - PA4/ADC4 INT0/PCINT4 0 0 0 0 0 0 - INT0 ENABLE INT0 ENABLE INT0 INPUT/ PCINT4 INPUT ADC4 INPUT
Table 13-5.
Signal Name PUOE PUOV DDOE DDOV PVOE PVOV PTOE DIEOE DIEOV DI AIO
Overriding Signals for Alternate Functions in PA3:PA0
PA3/ADC3/ PCINT3 0 0 0 0 0 0 - 0 0 PCINT3 INPUT ADC3 INPUT PA2/ADC2/ PCINT2 0 0 0 0 0 0 - 0 0 PCINT2 INPUT ADC2 INPUT PA1/ADC1/ PCINT1 0 0 0 0 0 0 - 0 0 PCINT1 INPUT ADC1 INPUT PA0/ADC0/ PCINT0 0 0 0 0 0 0 - 0 0 PCINT0 INPUT ADC0 INPUT
69
2548E-AVR-07/06
13.3.2
Alternate Functions of Port B The Port B pins with alternate functions are shown in Table 13-6. Table 13-6.
Port Pin PB7 PB6 PB5 PB4 PB3 PB2 PB1 PB0
Port B Pins Alternate Functions
Alternate Functions OC0B (Output Compare and PWM Output B for Timer/Counter0) PCINT15 (Pin Change Interrupt 15) OC0A (Output Compare and PWM Output A for Timer/Counter0) PCINT14 (Pin Change Interrupt 14) PCINT13 (Pin Change Interrupt 13) PCINT12 (Pin Change Interrupt 12) TCK (JTAG Test Clock) PCINT11 (Pin Change Interrupt 11) TMS (JTAG Test Mode Select) PCINT10 (Pin Change Interrupt 10) TDI (JTAG Test Data Input/) PCINT9 (Pin Change Interrupt 9) TDO (JTAG Test Data Output) PCINT8 (Pin Change Interrupt 8)
The alternate pin configuration is as follows: * OC0B/PCINT15 - Port B, Bit 7 OC0B, Output Compare Match B output: The PB7 pin can serve as an external output for the Timer/Counter0 Output Compare. The pin has to be configured as an output (DDB7 set (one)) to serve this function. The OC0B pin is also the output pin for the PWM mode timer function. PCINT15, Pin Change Interrupt Source 15. The PB7 pin can serve as external interrupt source to the MCU. * OC0A/PCINT14 - Port B, Bit 6 OC0A, Output Compare Match A output: The PB6 pin can serve as an external output for the Timer/Counter0 Output Compare. The pin has to be configured as an output (DDB6 set (one)) to serve this function. The OC0A pin is also the output pin for the PWM mode timer function. PCINT14, Pin Change Interrupt Source 14. The PB6 pin can serve as external interrupt source to the MCU. * PCINT13:12 - Port B, Bit 5:4 PCINT13 - PCINT12, Pin Change Interrupt Source 13:12. The PB5:4 pinS can serve as external interrupt sources to the MCU. * TCK/PCINT11 - Port B, Bit 3 TCK, JTAG Test Clock: JTAG operation is synchronous to TCK. When the JTAG Interface is enabled, this pin can not be used as an I/O pin. PCINT11, Pin Change Interrupt Source 11. The PB3 pin can serve as external interrupt source to the MCU.
70
ATmega406
2548E-AVR-07/06
ATmega406
* TMS/PCINT10 - Port B, Bit 2 TMS, JTAG Test Mode Select: This pin is used for navigating through the TAP-controller state machine. When the JTAG interface is enabled, this pin can not be used as an I/O pin. PCINT10, Pin Change Interrupt Source 10. The PB2 pin can serve as external interrupt source to the MCU. * TDI/PCINT9 - Port B, Bit 1 TDI, JTAG Test Data Input: Serial input data to be shifted in the Instruction Register or Data Register (scan chains). When the JTAG Interface is enabled, this pin can not be used as I/O pin. PCINT9, Pin Change Interrupt Source 9. The PB1 pin can serve as external interrupt source to the MCU. * TDO/PCINT8 - Port B, Bit 0 TDO, JTAG Test Data Output: Serial output data from Instruction Register or Data Register. When the JTAG Interface is enabled, this pin can not be used as an I/O pin. PCINT8, Pin Change Interrupt Source 8. The PB0 pin can serve as external interrupt source to the MCU. Table 13-7 and Table 13-8 relate the alternate functions of Port B to the overriding signals shown in Figure 13-5 on page 66. Table 13-7.
Signal Name PUOE PUOV DDOE DDOV PVOE PVOV PTOE DIEOE DIEOV DI AIO
Overriding Signals for Alternate Functions in PB7:PB4
PB7/OCOB/ PCINT15 0 0 0 0 OC0B Enable OC0B - 0 0 PCINT15 INPUT - PB6/OCOA/ PCINT14 0 0 0 0 OC0A Enable OC0A - 0 0 PCINT14 INPUT - - 0 0 PCINT13 INPUT - PB5/ PCINT13 0 0 0 0 PB4/ PCINT12 0 0 0 0 0 0 - 0 0 PCINT12 INPUT -
71
2548E-AVR-07/06
. Table 13-8.
Signal Name PUOE PUOV DDOE DDOV PVOE PVOV PTOE DIEOE DIEOV DI AIO
Overriding Signals for Alternate Functions in PB3:PB0
PB3/TCK/ PCINT11 JTAGEN 1 JTAGEN 0 0 0 - JTAGEN 0 TCK/PCINT11 INPUT - PB2/TMS/ PCINT10 JTAGEN 1 JTAGEN 0 0 0 - JTAGEN 0 TMS/PCINT10 INPUT - PB1/TDI/ PCINT9 JTAGEN 1 JTAGEN 0 0 0 - JTAGEN 0 TDI/PCINT9 INPUT - PB0/TDO/ PCINT8 JTAGEN 0 JTAGEN SHIFT_IR + SHIFT_DR JTAGEN TDO - JTAGEN 0 PCINT8 INPUT -
13.3.3
Alternate Functions of Port D The Port D pins with alternate functions are shown in Table 13-9. Table 13-9.
Port Pin PD0
Port D Pins Alternate Functions
Alternate Function T0 (Timer/Counter0 Clock Input)
The alternate pin configuration is as follows: * T0 - Port B, Bit 0 T0, Timer/Counter0 Counter Source. Table 13-10 on page 73 relates the alternate functions of Port D to the overriding signals shown in Figure 13-5 on page 66.
72
ATmega406
2548E-AVR-07/06
ATmega406
Table 13-10. Overriding Signals for Alternate Functions in PD1:PD0
Signal Name PUOE PUOV DDOE DDOV PVOE PVOV PTOE DIEOE DIEOV DI AIO - 0 0 - - PD1 0 0 0 0 PD0/T0 0 0 0 0 0 0 - 0 0 T0 Input -
13.4
13.4.1
Register Description
MCUCR - MCU Control Register
Bit 0x35 (0x55) Read/Write Initial Value 7 JTD R/W 0 6 - R 0 5 - R 0 4 PUD R/W 0 3 - R 0 2 - R 0 1 IVSEL R/W 0 0 IVCE R/W 0 MCUCR
* Bit 4 - PUD: Pull-up Disable When this bit is written to one, the pull-ups in the I/O ports are disabled even if the DDxn and PORTxn Registers are configured to enable the pull-ups ({DDxn, PORTxn} = 0b01). See "Configuring the Pin" on page 61 for more details about this feature. 13.4.2 PORTA - Port A Data Register
Bit 0x02 (0x22) Read/Write Initial Value 7
PORTA7
6
PORTA6
5
PORTA5
4
PORTA4
3
PORTA3
2
PORTA2
1
PORTA1
0
PORTA0
PORTA
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
13.4.3
DDRA - Port A Data Direction Register
Bit 0x01 (0x21) Read/Write Initial Value 7
DDA7
6
DDA6
5
DDA5
4
DDA4
3 DDA3 R/W 0
2 DDA2 R/W 0
1 DDA1 R/W 0
0 DDA0 R/W 0 DDRA
R/W 0
R/W 0
R/W 0
R/W 0
13.4.4
PINA - Port A Input Pins Address
Bit 0x00 (0x20) Read/Write Initial Value 7
PINA7
6
PINA6
5
PINA5
4
PINA4
3 PINA3 R/W N/A
2 PINA2 R/W N/A
1 PINA1 R/W N/A
0 PINA0 R/W N/A PINA
R/W N/A
R/W N/A
R/W N/A
R/W N/A
73
2548E-AVR-07/06
13.4.5
PORTB - Port B Data Register
Bit 0x05 (0x25) Read/Write Initial Value 7
PORTB7
6
PORTB6
5
PORTB5
4
PORTB4
3
PORTB3
2
PORTB2
1
PORTB1
0
PORTB0 PORTB
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
13.4.6
DDRB - Port B Data Direction Register
Bit 0x04 (0x24) Read/Write Initial Value 7
DDB7
6 DDB6 R/W 0
5 DDB5 R/W 0
4 DDB4 R/W 0
3 DDB3 R/W 0
2 DDB2 R/W 0
1 DDB1 R/W 0
0 DDB0 R/W 0 DDRB
R/W 0
13.4.7
PINB - Port B Input Pins Address
Bit 0x03 (0x23) Read/Write Initial Value 7
PINB7
6 PINB6 R N/A
5 PINB5 R N/A
4 PINB4 R N/A
3 PINB3 R N/A
2 PINB2 R N/A
1 PINB1 R N/A
0 PINB0 R N/A PINB
R N/A
13.4.8
PORTD - Port D Data Register
Bit 0x0B (0x2B) Read/Write Initial Value 7
-
6
-
5
-
4
-
3
-
2
-
1
PORTD1
0
PORTD0 PORTD
R 0
R 0
R 0
R 0
R 0
R 0
R/W 0
R/W 0
13.4.9
DDRD - Port D Data Direction Register
Bit 0x0A (0x2A) Read/Write Initial Value 7 - R 0 6 - R 0 5 - R 0 4 - R 0 3
-
2
-
1 DDD1 R/W 0
0 DDD0 R/W 0 DDRD
R 0
R 0
13.4.10
PIND - Port D Input Pins Address
Bit 0x09 (0x29) Read/Write Initial Value 7 - R 0 6 - R 0 5 - R 0 4 - R 0 3
-
2
-
1 PIND1 R/W N/A
0 PIND0 R/W N/A PIND
R 0
R 0
74
ATmega406
2548E-AVR-07/06
ATmega406
14. High Voltage I/O Ports
All high voltage AVR ports have true Read-Modify-Write functionality when used as general digital I/O ports. This means that the state of one port pin can be changed without unintentionally changing the state of any other pin with the SBI and CBI instructions. All high voltage I/O pins have protection Zener diodes to Ground as indicated in Figure 14-1. See "Electrical Characteristics" on page 225 for a complete list of parameters. Figure 14-1. High Voltage I/O Pin Equivalent Schematic
Pxn
Logic Cpin
See Figure "General High Voltage Digital I/O" for Details
All registers and bit references in this section are written in general form. A lower case "x" represents the numbering letter for the port, and a lower case "n" represents the bit number. However, when using the register or bit defines in a program, the precise form must be used. For example, PORTC3 for bit number three in Port C, here documented generally as PORTxn. The physical I/O Registers and bit locations are listed in "Register Description for High Voltage Output Ports" on page 76. One I/O Memory address location is allocated for each high voltage port, the Data Register - PORTx. The Data Register is read/write. Using the I/O port as General Digital Output is described in "High Voltage Ports as General Digital Outputs" on page 75.
14.1
High Voltage Ports as General Digital Outputs
The high voltage ports are high voltage tolerant open collector output ports. Figure 14-2 shows a functional description of one output port pin, here generically called Pxn.
75
2548E-AVR-07/06
Figure 14-2. General High Voltage Digital I/O(1)
Pxn
Q
D
PORTxn Q CLR
RESET
WRx RRx
WRx: RRx:
WRITE PORTx READ PORTx REGISTER
Note:
1. WRx and RRx are common to all pins within the same port.
14.2
Configuring the Pin
Each port pin has one register bit: PORTxn. As shown in "Register Description for High Voltage Output Ports" on page 76, the PORTxn bits are accessed at the PORTx I/O address. If PORTxn is written logic one, the port pin is driven low (zero). If PORTxn is written logic zero, the port pin is tri-stated. The port pins are tri-stated when a reset condition becomes active, even if no clocks are running.
14.3
14.3.1
Register Description for High Voltage Output Ports
PORTC - Port C Data Register
Bit 0x08 (0x28) Read/Write Initial Value 7
-
6
5
4
3
2
DATA BUS
1
0
PORTC0 PORTC
R 0
R 0
R 0
R 0
R 0
R 0
R 0
R/W 0
76
ATmega406
2548E-AVR-07/06
ATmega406
15. 8-bit Timer/Counter0 with PWM
Timer/Counter0 is a general purpose 8-bit Timer/Counter module, with two independent Output Compare Units, and with PWM support. It allows accurate program execution timing (event management) and wave generation. The main features are: * * * * * * *
Two Independent Output Compare Units Double Buffered Output Compare Registers Clear Timer on Compare Match (Auto Reload) Glitch Free, Phase Correct Pulse Width Modulator (PWM) Variable PWM Period Frequency Generator Three Independent Interrupt Sources (TOV0, OCF0A, and OCF0B)
15.1
Overview
A simplified block diagram of the 8-bit Timer/Counter is shown in Figure 15-1. For the actual placement of I/O pins, refer to "Pinout ATmega406." on page 2. CPU accessible I/O Registers, including I/O bits and I/O pins, are shown in bold. The device-specific I/O Register and bit locations are listed in the "8-bit Timer/Counter Register Description" on page 88. The PRTIM0 bit in "PRR0 - Power Reduction Register 0" on page 36 must be written to zero to enable Timer/Counter0 module. Figure 15-1. 8-bit Timer/Counter Block Diagram
Count Clear Direction Control Logic TOVn (Int.Req.) clkTn T/C Oscillator TOP BOTTOM Prescaler clkI/O TOSC2 TOSC1
Timer/Counter TCNTn
=
=0
OCnA (Int.Req.)
=
OCRnA Fixed TOP Value
Waveform Generation
OCnA
DATA BUS
OCnB (Int.Req.) Waveform Generation OCnB
=
OCRnB
TCCRnA
TCCRnB
15.1.1
Definitions Many register and bit references in this section are written in general form. A lower case "n" replaces the Timer/Counter number, in this case 0. A lower case "x" replaces the Output Compare Unit, in this case Compare Unit A or Compare Unit B. However, when using the register or bit defines in a program, the precise form must be used, i.e., TCNT0 for accessing Timer/Counter0 counter value and so on. 77
2548E-AVR-07/06
The definitions in Table 15-1 are also used extensively throughout the document. Table 15-1. BOTTOM MAX TOP Definitions The counter reaches the BOTTOM when it becomes 0x00. The counter reaches its MAXimum when it becomes 0xFF (decimal 255). The counter reaches the TOP when it becomes equal to the highest value in the count sequence. The TOP value can be assigned to be the fixed value 0xFF (MAX) or the value stored in the OCR0A Register. The assignment is dependent on the mode of operation.
15.1.2
Registers The Timer/Counter (TCNT0) and Output Compare Registers (OCR0A and OCR0B) are 8-bit registers. Interrupt request (abbreviated to Int.Req. in the figure) signals are all visible in the Timer Interrupt Flag Register (TIFR0). All interrupts are individually masked with the Timer Interrupt Mask Register (TIMSK0). TIFR0 and TIMSK0 are not shown in the figure. The Timer/Counter can be clocked internally, via the prescaler, or by an external clock source on the T0 pin. The Clock Select logic block controls which clock source and edge the Timer/Counter uses to increment (or decrement) its value. The Timer/Counter is inactive when no clock source is selected. The output from the Clock Select logic is referred to as the timer clock (clkT0). The double buffered Output Compare Registers (OCR0A and OCR0B) are compared with the Timer/Counter value at all times. The result of the compare can be used by the Waveform Generator to generate a PWM or variable frequency output on the Output Compare pins (OC0A and OC0B). See Section "15.4.3" on page 80. for details. The compare match event will also set the Compare Flag (OCF0A or OCF0B) which can be used to generate an Output Compare interrupt request.
15.2
Timer/Counter Clock Sources
The Timer/Counter can be clocked by an internal or an external clock source. The clock source is selected by the Clock Select logic which is controlled by the Clock Select (CS02:0) bits located in the Timer/Counter Control Register (TCCR0B). For details on clock sources and prescaler, see "Timer/Counter0 and Timer/Counter1 Prescalers" on page 103.
15.3
Counter Unit
The main part of the 8-bit Timer/Counter is the programmable bi-directional counter unit. Figure 15-2 shows a block diagram of the counter and its surroundings. Figure 15-2. Counter Unit Block Diagram
DATA BUS
TOVn (Int.Req.)
Clock Select count TCNTn clear direction ( From Prescaler ) bottom top Control Logic clkTn Edge Detector Tn
Signal description (internal signals):
78
ATmega406
2548E-AVR-07/06
ATmega406
count direction clear clkTn top bottom Increment or decrement TCNT0 by 1. Select between increment and decrement. Clear TCNT0 (set all bits to zero). Timer/Counter clock, referred to as clkT0 in the following. Signalize that TCNT0 has reached maximum value. Signalize that TCNT0 has reached minimum value (zero).
Depending of the mode of operation used, the counter is cleared, incremented, or decremented at each timer clock (clkT0). clkT0 can be generated from an external or internal clock source, selected by the Clock Select bits (CS02:0). When no clock source is selected (CS02:0 = 0) the timer is stopped. However, the TCNT0 value can be accessed by the CPU, regardless of whether clkT0 is present or not. A CPU write overrides (has priority over) all counter clear or count operations. The counting sequence is determined by the setting of the WGM01 and WGM00 bits located in the Timer/Counter Control Register (TCCR0A) and the WGM02 bit located in the Timer/Counter Control Register B (TCCR0B). There are close connections between how the counter behaves (counts) and how waveforms are generated on the Output Compare outputs OC0A and OC0B. For more details about advanced counting sequences and waveform generation, see "Modes of Operation" on page 82. The Timer/Counter Overflow Flag (TOV0) is set according to the mode of operation selected by the WGM02:0 bits. TOV0 can be used for generating a CPU interrupt.
15.4
Output Compare Unit
The 8-bit comparator continuously compares TCNT0 with the Output Compare Registers (OCR0A and OCR0B). Whenever TCNT0 equals OCR0A or OCR0B, the comparator signals a match. A match will set the Output Compare Flag (OCF0A or OCF0B) at the next timer clock cycle. If the corresponding interrupt is enabled, the Output Compare Flag generates an Output Compare interrupt. The Output Compare Flag is automatically cleared when the interrupt is executed. Alternatively, the flag can be cleared by software by writing a logical one to its I/O bit location. The Waveform Generator uses the match signal to generate an output according to operating mode set by the WGM02:0 bits and Compare Output mode (COM0x1:0) bits. The max and bottom signals are used by the Waveform Generator for handling the special cases of the extreme values in some modes of operation ("Modes of Operation" on page 82). Figure 15-3 shows a block diagram of the Output Compare unit.
79
2548E-AVR-07/06
Figure 15-3. Output Compare Unit, Block Diagram
DATA BUS
OCRnx
TCNTn
= (8-bit Comparator )
OCFnx (Int.Req.)
top bottom FOCn
Waveform Generator
OCnx
WGMn1:0
COMnx1:0
The OCR0x Registers are double buffered when using any of the Pulse Width Modulation (PWM) modes. For the normal and Clear Timer on Compare (CTC) modes of operation, the double buffering is disabled. The double buffering synchronizes the update of the OCR0x Compare Registers to either top or bottom of the counting sequence. The synchronization prevents the occurrence of odd-length, non-symmetrical PWM pulses, thereby making the output glitch-free. The OCR0x Register access may seem complex, but this is not case. When the double buffering is enabled, the CPU has access to the OCR0x Buffer Register, and if double buffering is disabled the CPU will access the OCR0x directly. 15.4.1 Force Output Compare In non-PWM waveform generation modes, the match output of the comparator can be forced by writing a one to the Force Output Compare (FOC0x) bit. Forcing compare match will not set the OCF0x Flag or reload/clear the timer, but the OC0x pin will be updated as if a real compare match had occurred (the COM0x1:0 bits settings define whether the OC0x pin is set, cleared or toggled). Compare Match Blocking by TCNT0 Write All CPU write operations to the TCNT0 Register will block any compare match that occur in the next timer clock cycle, even when the timer is stopped. This feature allows OCR0x to be initialized to the same value as TCNT0 without triggering an interrupt when the Timer/Counter clock is enabled. Using the Output Compare Unit Since writing TCNT0 in any mode of operation will block all compare matches for one timer clock cycle, there are risks involved when changing TCNT0 when using the Output Compare Unit, independently of whether the Timer/Counter is running or not. If the value written to TCNT0 equals the OCR0x value, the compare match will be missed, resulting in incorrect waveform generation. Similarly, do not write the TCNT0 value equal to BOTTOM when the counter is downcounting. The setup of the OC0x should be performed before setting the Data Direction Register for the port pin to output. The easiest way of setting the OC0x value is to use the Force Output Com-
15.4.2
15.4.3
80
ATmega406
2548E-AVR-07/06
ATmega406
pare (FOC0x) strobe bits in Normal mode. The OC0x Registers keep their values even when changing between Waveform Generation modes. Be aware that the COM0x1:0 bits are not double buffered together with the compare value. Changing the COM0x1:0 bits will take effect immediately.
15.5
Compare Match Output Unit
The Compare Output mode (COM0x1:0) bits have two functions. The Waveform Generator uses the COM0x1:0 bits for defining the Output Compare (OC0x) state at the next compare match. Also, the COM0x1:0 bits control the OC0x pin output source. Figure 15-4 shows a simplified schematic of the logic affected by the COM0x1:0 bit setting. The I/O Registers, I/O bits, and I/O pins in the figure are shown in bold. Only the parts of the general I/O port control registers (DDR and PORT) that are affected by the COM0x1:0 bits are shown. When referring to the OC0x state, the reference is for the internal OC0x Register, not the OC0x pin. If a system reset occur, the OC0x Register is reset to "0". Figure 15-4. Compare Match Output Unit, Schematic
COMnx1 COMnx0 FOCn
Waveform Generator
D
Q
1 OCnx Pin
OCnx D Q
0
DATA BUS
PORT D Q
DDR
clk I/O
The general I/O port function is overridden by the Output Compare (OC0x) from the Waveform Generator if either of the COM0x1:0 bits are set. However, the OC0x pin direction (input or output) is still controlled by the Data Direction Register (DDR) for the port pin. The Data Direction Register bit for the OC0x pin (DDR_OC0x) must be set as output before the OC0x value is visible on the pin. The port override function is independent of the Waveform Generation mode. The design of the Output Compare pin logic allows initialization of the OC0x state before the output is enabled. Note that some COM0x1:0 bit settings are reserved for certain modes of operation. See Section "15.8" on page 88. 15.5.1 Compare Output Mode and Waveform Generation The Waveform Generator uses the COM0x1:0 bits differently in Normal, CTC, and PWM modes. For all modes, setting the COM0x1:0 = 0 tells the Waveform Generator that no action on the OC0x Register is to be performed on the next compare match. For compare output actions in the non-PWM modes refer to Table 15-2 on page 88. For fast PWM mode, refer to Table 15-3 on page 88, and for phase correct PWM refer to Table 15-4 on page 89.
81
2548E-AVR-07/06
A change of the COM0x1:0 bits state will have effect at the first compare match after the bits are written. For non-PWM modes, the action can be forced to have immediate effect by using the FOC0x strobe bits.
15.6
Modes of Operation
The mode of operation, i.e., the behavior of the Timer/Counter and the Output Compare pins, is defined by the combination of the Waveform Generation mode (WGM02:0) and Compare Output mode (COM0x1:0) bits. The Compare Output mode bits do not affect the counting sequence, while the Waveform Generation mode bits do. The COM0x1:0 bits control whether the PWM output generated should be inverted or not (inverted or non-inverted PWM). For non-PWM modes the COM0x1:0 bits control whether the output should be set, cleared, or toggled at a compare match (See Section "15.5" on page 81.). For detailed timing information refer to "Timer/Counter Timing Diagrams" on page 86.
15.6.1
Normal Mode The simplest mode of operation is the Normal mode (WGM02:0 = 0). In this mode the counting direction is always up (incrementing), and no counter clear is performed. The counter simply overruns when it passes its maximum 8-bit value (TOP = 0xFF) and then restarts from the bottom (0x00). In normal operation the Timer/Counter Overflow Flag (TOV0) will be set in the same timer clock cycle as the TCNT0 becomes zero. The TOV0 Flag in this case behaves like a ninth bit, except that it is only set, not cleared. However, combined with the timer overflow interrupt that automatically clears the TOV0 Flag, the timer resolution can be increased by software. There are no special cases to consider in the Normal mode, a new counter value can be written anytime. The Output Compare unit can be used to generate interrupts at some given time. Using the Output Compare to generate waveforms in Normal mode is not recommended, since this will occupy too much of the CPU time.
15.6.2
Clear Timer on Compare Match (CTC) Mode In Clear Timer on Compare or CTC mode (WGM02:0 = 2), the OCR0A Register is used to manipulate the counter resolution. In CTC mode the counter is cleared to zero when the counter value (TCNT0) matches the OCR0A. The OCR0A defines the top value for the counter, hence also its resolution. This mode allows greater control of the compare match output frequency. It also simplifies the operation of counting external events. The timing diagram for the CTC mode is shown in Figure 15-5. The counter value (TCNT0) increases until a compare match occurs between TCNT0 and OCR0A, and then counter (TCNT0) is cleared.
82
ATmega406
2548E-AVR-07/06
ATmega406
Figure 15-5. CTC Mode, Timing Diagram
OCnx Interrupt Flag Set
TCNTn
OCn (Toggle) Period
1 2 3 4
(COMnx1:0 = 1)
An interrupt can be generated each time the counter value reaches the TOP value by using the OCF0A Flag. If the interrupt is enabled, the interrupt handler routine can be used for updating the TOP value. However, changing TOP to a value close to BOTTOM when the counter is running with none or a low prescaler value must be done with care since the CTC mode does not have the double buffering feature. If the new value written to OCR0A is lower than the current value of TCNT0, the counter will miss the compare match. The counter will then have to count to its maximum value (0xFF) and wrap around starting at 0x00 before the compare match can occur. For generating a waveform output in CTC mode, the OC0A output can be set to toggle its logical level on each compare match by setting the Compare Output mode bits to toggle mode (COM0A1:0 = 1). The OC0A value will not be visible on the port pin unless the data direction for the pin is set to output. The waveform generated will have a maximum frequency of fOC0 = fclk_I/O/2 when OCR0A is set to zero (0x00). The waveform frequency is defined by the following equation: f clk_I/O f OCnx = ------------------------------------------------2 N ( 1 + OCRnx ) The N variable represents the prescale factor (1, 8, 64, 256, or 1024). As for the Normal mode of operation, the TOV0 Flag is set in the same timer clock cycle that the counter counts from MAX to 0x00. 15.6.3 Fast PWM Mode The fast Pulse Width Modulation or fast PWM mode (WGM02:0 = 3 or 7) provides a high frequency PWM waveform generation option. The fast PWM differs from the other PWM option by its single-slope operation. The counter counts from BOTTOM to TOP then restarts from BOTTOM. TOP is defined as 0xFF when WGM2:0 = 3, and OCR0A when WGM2:0 = 7. In noninverting Compare Output mode, the Output Compare (OC0x) is cleared on the compare match between TCNT0 and OCR0x, and set at BOTTOM. In inverting Compare Output mode, the output is set on compare match and cleared at BOTTOM. Due to the single-slope operation, the operating frequency of the fast PWM mode can be twice as high as the phase correct PWM mode that use dual-slope operation. This high frequency makes the fast PWM mode well suited for power regulation, rectification, and DAC applications. High frequency allows physically small sized external components (coils, capacitors), and therefore reduces total system cost. In fast PWM mode, the counter is incremented until the counter value matches the TOP value. The counter is then cleared at the following timer clock cycle. The timing diagram for the fast
83
2548E-AVR-07/06
PWM mode is shown in Figure 15-6. The TCNT0 value is in the timing diagram shown as a histogram for illustrating the single-slope operation. The diagram includes non-inverted and inverted PWM outputs. The small horizontal line marks on the TCNT0 slopes represent compare matches between OCR0x and TCNT0. Figure 15-6. Fast PWM Mode, Timing Diagram
OCRnx Interrupt Flag Set
OCRnx Update and TOVn Interrupt Flag Set
TCNTn
OCn OCn
(COMnx1:0 = 2)
(COMnx1:0 = 3)
Period
1
2
3
4
5
6
7
The Timer/Counter Overflow Flag (TOV0) is set each time the counter reaches TOP. If the interrupt is enabled, the interrupt handler routine can be used for updating the compare value. In fast PWM mode, the compare unit allows generation of PWM waveforms on the OC0x pins. Setting the COM0x1:0 bits to two will produce a non-inverted PWM and an inverted PWM output can be generated by setting the COM0x1:0 to three: Setting the COM0A1:0 bits to one allows the OC0A pin to toggle on Compare Matches if the WGM02 bit is set. This option is not available for the OC0B pin (see Table 15-6 on page 89). The actual OC0x value will only be visible on the port pin if the data direction for the port pin is set as output. The PWM waveform is generated by setting (or clearing) the OC0x Register at the compare match between OCR0x and TCNT0, and clearing (or setting) the OC0x Register at the timer clock cycle the counter is cleared (changes from TOP to BOTTOM). The PWM frequency for the output can be calculated by the following equation: f clk_I/O f OCnxPWM = ----------------N 256 The N variable represents the prescale factor (1, 8, 64, 256, or 1024). The extreme values for the OCR0A Register represents special cases when generating a PWM waveform output in the fast PWM mode. If the OCR0A is set equal to BOTTOM, the output will be a narrow spike for each MAX+1 timer clock cycle. Setting the OCR0A equal to MAX will result in a constantly high or low output (depending on the polarity of the output set by the COM0A1:0 bits.) A frequency (with 50% duty cycle) waveform output in fast PWM mode can be achieved by setting OC0x to toggle its logical level on each compare match (COM0x1:0 = 1). The waveform generated will have a maximum frequency of fOC0 = fclk_I/O/2 when OCR0A is set to zero. This
84
ATmega406
2548E-AVR-07/06
ATmega406
feature is similar to the OC0A toggle in CTC mode, except the double buffer feature of the Output Compare unit is enabled in the fast PWM mode. 15.6.4 Phase Correct PWM Mode The phase correct PWM mode (WGM02:0 = 1 or 5) provides a high resolution phase correct PWM waveform generation option. The phase correct PWM mode is based on a dual-slope operation. The counter counts repeatedly from BOTTOM to TOP and then from TOP to BOTTOM. TOP is defined as 0xFF when WGM2:0 = 1, and OCR0A when WGM2:0 = 5. In noninverting Compare Output mode, the Output Compare (OC0x) is cleared on the compare match between TCNT0 and OCR0x while upcounting, and set on the compare match while downcounting. In inverting Output Compare mode, the operation is inverted. The dual-slope operation has lower maximum operation frequency than single slope operation. However, due to the symmetric feature of the dual-slope PWM modes, these modes are preferred for motor control applications. In phase correct PWM mode the counter is incremented until the counter value matches TOP. When the counter reaches TOP, it changes the count direction. The TCNT0 value will be equal to TOP for one timer clock cycle. The timing diagram for the phase correct PWM mode is shown on Figure 15-7. The TCNT0 value is in the timing diagram shown as a histogram for illustrating the dual-slope operation. The diagram includes non-inverted and inverted PWM outputs. The small horizontal line marks on the TCNT0 slopes represent compare matches between OCR0x and TCNT0. Figure 15-7. Phase Correct PWM Mode, Timing Diagram
OCnx Interrupt Flag Set
OCRnx Update
TOVn Interrupt Flag Set
TCNTn
OCnx OCnx
(COMnx1:0 = 2)
(COMnx1:0 = 3)
Period
1
2
3
The Timer/Counter Overflow Flag (TOV0) is set each time the counter reaches BOTTOM. The Interrupt Flag can be used to generate an interrupt each time the counter reaches the BOTTOM value. In phase correct PWM mode, the compare unit allows generation of PWM waveforms on the OC0x pins. Setting the COM0x1:0 bits to two will produce a non-inverted PWM. An inverted PWM output can be generated by setting the COM0x1:0 to three: Setting the COM0A0 bits to
85
2548E-AVR-07/06
one allows the OC0A pin to toggle on Compare Matches if the WGM02 bit is set. This option is not available for the OC0B pin (see Table 15-7 on page 90). The actual OC0x value will only be visible on the port pin if the data direction for the port pin is set as output. The PWM waveform is generated by clearing (or setting) the OC0x Register at the compare match between OCR0x and TCNT0 when the counter increments, and setting (or clearing) the OC0x Register at compare match between OCR0x and TCNT0 when the counter decrements. The PWM frequency for the output when using phase correct PWM can be calculated by the following equation: f clk_I/O f OCnxPCPWM = ----------------N 510 The N variable represents the prescale factor (1, 8, 64, 256, or 1024). The extreme values for the OCR0A Register represent special cases when generating a PWM waveform output in the phase correct PWM mode. If the OCR0A is set equal to BOTTOM, the output will be continuously low and if set equal to MAX the output will be continuously high for non-inverted PWM mode. For inverted PWM the output will have the opposite logic values. At the very start of period 2 in Figure 15-7 OCnx has a transition from high to low even though there is no Compare Match. The point of this transition is to guarantee symmetry around BOTTOM. There are two cases that give a transition without Compare Match. * OCRnx changes its value from MAX, like in Figure 15-7. When the OCR0A value is MAX the OCn pin value is the same as the result of a down-counting Compare Match. To ensure symmetry around BOTTOM the OCnx value at MAX must correspond to the result of an upcounting Compare Match. * The timer starts counting from a value higher than the one in OCRnx, and for that reason misses the Compare Match and hence the OCnx change that would have happened on the way up.
15.7
Timer/Counter Timing Diagrams
The Timer/Counter is a synchronous design and the timer clock (clkT0) is therefore shown as a clock enable signal in the following figures. The figures include information on when interrupt flags are set. Figure 15-8 contains timing data for basic Timer/Counter operation. The figure shows the count sequence close to the MAX value in all modes other than phase correct PWM mode. Figure 15-8. Timer/Counter Timing Diagram, no Prescaling
clkI/O clkTn
(clkI/O /1)
TCNTn
MAX - 1
MAX
BOTTOM
BOTTOM + 1
TOVn
Figure 15-9 shows the same timing data, but with the prescaler enabled.
86
ATmega406
2548E-AVR-07/06
ATmega406
Figure 15-9. Timer/Counter Timing Diagram, with Prescaler (fclk_I/O/8)
clkI/O clkTn
(clkI/O /8)
TCNTn
MAX - 1
MAX
BOTTOM
BOTTOM + 1
TOVn
Figure 15-10 shows the setting of OCF0B in all modes and OCF0A in all modes except CTC mode and PWM mode, where OCR0A is TOP. Figure 15-10. Timer/Counter Timing Diagram, Setting of OCF0x, with Prescaler (fclk_I/O/8)
clkI/O clkTn
(clkI/O /8)
TCNTn
OCRnx - 1
OCRnx
OCRnx + 1
OCRnx + 2
OCRnx
OCRnx Value
OCFnx
Figure 15-11 shows the setting of OCF0A and the clearing of TCNT0 in CTC mode and fast PWM mode where OCR0A is TOP. Figure 15-11. Timer/Counter Timing Diagram, Clear Timer on Compare Match mode, with Prescaler (fclk_I/O/8)
clkI/O clkTn
(clkI/O /8)
TCNTn (CTC) OCRnx
TOP - 1
TOP
BOTTOM
BOTTOM + 1
TOP
OCFnx
87
2548E-AVR-07/06
15.8
15.8.1
8-bit Timer/Counter Register Description
TCCR0A - Timer/Counter Control Register A
Bit 0x24 (0x44) Read/Write Initial Value 7
COM0A1
6
COM0A0
5
COM0B1
4
COM0B0
3
-
2
-
1
WGM01
0
WGM00 TCCR0A
R/W 0
R/W 0
R/W 0
R/W 0
R 0
R 0
R/W 0
R/W 0
* Bits 7:6 - COM0A1:0: Compare Match Output A Mode These bits control the Output Compare pin (OC0A) behavior. If one or both of the COM0A1:0 bits are set, the OC0A output overrides the normal port functionality of the I/O pin it is connected to. However, note that the Data Direction Register (DDR) bit corresponding to the OC0A pin must be set in order to enable the output driver. When OC0A is connected to the pin, the function of the COM0A1:0 bits depends on the WGM02:0 bit setting. Table 15-2 shows the COM0A1:0 bit functionality when the WGM02:0 bits are set to a normal or CTC mode (non-PWM). Table 15-2.
COM0A1 0 0 1 1
Compare Output Mode, non-PWM Mode
COM0A0 0 1 0 1 Description Normal port operation, OC0A disconnected. Toggle OC0A on Compare Match Clear OC0A on Compare Match Set OC0A on Compare Match
Table 15-3 shows the COM0A1:0 bit functionality when the WGM01:0 bits are set to fast PWM mode. Table 15-3.
COM0A1 0 0 1 1 Note:
Compare Output Mode, Fast PWM Mode(1)
COM0A0 0 1 0 1 Description Normal port operation, OC0A disconnected. WGM02 = 0: Normal Port Operation, OC0A Disconnected. WGM02 = 1: Toggle OC0A on Compare Match. Clear OC0A on Compare Match, set OC0A at TOP Set OC0A on Compare Match, clear OC0A at TOP
1. A special case occurs when OCR0A equals TOP and COM0A1 is set. In this case, the Compare Match is ignored, but the set or clear is done at TOP. See "Fast PWM Mode" on page 83 for more details.
88
ATmega406
2548E-AVR-07/06
ATmega406
Table 15-4 shows the COM0A1:0 bit functionality when the WGM02:0 bits are set to phase correct PWM mode. Table 15-4.
COM0A1 0 0 1 1 Note:
Compare Output Mode, Phase Correct PWM Mode(1)
COM0A0 0 1 0 1 Description Normal port operation, OC0A disconnected. WGM02 = 0: Normal Port Operation, OC0A Disconnected. WGM02 = 1: Toggle OC0A on Compare Match. Clear OC0A on Compare Match when up-counting. Set OC0A on Compare Match when down-counting. Set OC0A on Compare Match when up-counting. Clear OC0A on Compare Match when down-counting.
1. A special case occurs when OCR0A equals TOP and COM0A1 is set. In this case, the Compare Match is ignored, but the set or clear is done at TOP. See "Phase Correct PWM Mode" on page 85 for more details.
* Bits 5:4 - COM0B1:0: Compare Match Output B Mode These bits control the Output Compare pin (OC0B) behavior. If one or both of the COM0B1:0 bits are set, the OC0B output overrides the normal port functionality of the I/O pin it is connected to. However, note that the Data Direction Register (DDR) bit corresponding to the OC0B pin must be set in order to enable the output driver. When OC0B is connected to the pin, the function of the COM0B1:0 bits depends on the WGM02:0 bit setting. Table 15-5 shows the COM0B1:0 bit functionality when the WGM02:0 bits are set to a normal or CTC mode (non-PWM). Table 15-5.
COM0B1 0 0 1 1
Compare Output Mode, non-PWM Mode
COM0B0 0 1 0 1 Description Normal port operation, OC0B disconnected. Toggle OC0B on Compare Match Clear OC0B on Compare Match Set OC0B on Compare Match
Table 15-6 shows the COM0B1:0 bit functionality when the WGM02:0 bits are set to fast PWM mode. Table 15-6.
COM0B1 0 0 1 1 Note:
Compare Output Mode, Fast PWM Mode(1)
COM0B0 0 1 0 1 Description Normal port operation, OC0B disconnected. Reserved Clear OC0B on Compare Match, set OC0B at TOP Set OC0B on Compare Match, clear OC0B at TOP
1. A special case occurs when OCR0B equals TOP and COM0B1 is set. In this case, the Compare Match is ignored, but the set or clear is done at TOP. See "Fast PWM Mode" on page 83 for more details.
89
2548E-AVR-07/06
Table 15-7 shows the COM0B1:0 bit functionality when the WGM02:0 bits are set to phase correct PWM mode. Table 15-7.
COM0B1 0 0 1 1 Note:
Compare Output Mode, Phase Correct PWM Mode(1)
COM0B0 0 1 0 1 Description Normal port operation, OC0B disconnected. Reserved Clear OC0B on Compare Match when up-counting. Set OC0B on Compare Match when down-counting. Set OC0B on Compare Match when up-counting. Clear OC0B on Compare Match when down-counting.
1. A special case occurs when OCR0B equals TOP and COM0B1 is set. In this case, the Compare Match is ignored, but the set or clear is done at TOP. See "Phase Correct PWM Mode" on page 85 for more details.
* Bits 3, 2 - Res: Reserved Bits These bits are reserved bits in the ATmega406 and will always read as zero. * Bits 1:0 - WGM01:0: Waveform Generation Mode Combined with the WGM02 bit found in the TCCR0B Register, these bits control the counting sequence of the counter, the source for maximum (TOP) counter value, and what type of waveform generation to be used, see Table 15-8. Modes of operation supported by the Timer/Counter unit are: Normal mode (counter), Clear Timer on Compare Match (CTC) mode, and two types of Pulse Width Modulation (PWM) modes (see "Modes of Operation" on page 82). Table 15-8.
Mode 0 1 2 3 4 5 6 7 Notes:
Waveform Generation Mode Bit Description
WGM01 0 0 1 1 0 0 1 1 WGM00 0 1 0 1 0 1 0 1 Timer/Counter Mode of Operation Normal PWM, Phase Correct CTC Fast PWM Reserved PWM, Phase Correct Reserved Fast PWM TOP 0xFF 0xFF OCRA 0xFF - OCRA - OCRA Update of OCRx at Immediate TOP Immediate TOP - TOP - TOP TOV Flag Set on(1)(2) MAX BOTTOM MAX MAX - BOTTOM - TOP
WGM02 0 0 0 0 1 1 1 1
1. MAX = 0xFF 2. BOTTOM = 0x00
90
ATmega406
2548E-AVR-07/06
ATmega406
15.8.2 TCCR0B - Timer/Counter Control Register B
Bit 0x25 (0x45) Read/Write Initial Value 7
FOC0A
6
FOC0B
5
-
4
-
3
WGM02
2
CS02
1
CS01
0
CS00 TCCR0B
W 0
W 0
R 0
R 0
R/W 0
R/W 0
R/W 0
R/W 0
* Bit 7 - FOC0A: Force Output Compare A The FOC0A bit is only active when the WGM bits specify a non-PWM mode. However, for ensuring compatibility with future devices, this bit must be set to zero when TCCR0B is written when operating in PWM mode. When writing a logical one to the FOC0A bit, an immediate Compare Match is forced on the Waveform Generation unit. The OC0A output is changed according to its COM0A1:0 bits setting. Note that the FOC0A bit is implemented as a strobe. Therefore it is the value present in the COM0A1:0 bits that determines the effect of the forced compare. A FOC0A strobe will not generate any interrupt, nor will it clear the timer in CTC mode using OCR0A as TOP. The FOC0A bit is always read as zero. * Bit 6 - FOC0B: Force Output Compare B The FOC0B bit is only active when the WGM bits specify a non-PWM mode. However, for ensuring compatibility with future devices, this bit must be set to zero when TCCR0B is written when operating in PWM mode. When writing a logical one to the FOC0B bit, an immediate Compare Match is forced on the Waveform Generation unit. The OC0B output is changed according to its COM0B1:0 bits setting. Note that the FOC0B bit is implemented as a strobe. Therefore it is the value present in the COM0B1:0 bits that determines the effect of the forced compare. A FOC0B strobe will not generate any interrupt, nor will it clear the timer in CTC mode using OCR0B as TOP. The FOC0B bit is always read as zero. * Bits 5:4 - Res: Reserved Bits These bits are reserved bits in the ATmega406 and will always read as zero. * Bit 3 - WGM02: Waveform Generation Mode See the description in the "TCCR0A - Timer/Counter Control Register A" on page 88. * Bits 2:0 - CS02:0: Clock Select The three Clock Select bits select the clock source to be used by the Timer/Counter.
91
2548E-AVR-07/06
Table 15-9.
CS02 0 0 0 0 1 1 1 1
Clock Select Bit Description
Description CS00 0 1 0 1 0 1 0 1 No clock source (Timer/Counter stopped) clkI/O/(No prescaling) clkI/O/8 (From prescaler) clkI/O/64 (From prescaler) clkI/O/256 (From prescaler) clkI/O/1024 (From prescaler) External clock source on T0 pin. Clock on falling edge. External clock source on T0 pin. Clock on rising edge.
CS01 0 0 1 1 0 0 1 1
If external pin modes are used for the Timer/Counter0, transitions on the T0 pin will clock the counter even if the pin is configured as an output. This feature allows software control of the counting. 15.8.3 TCNT0 - Timer/Counter Register
Bit 0x26 (0x46) Read/Write Initial Value R/W 0 R/W 0 R/W 0 7 6 5 4 3 2 1 0 TCNT0 R/W 0 R/W 0 R/W 0 TCNT0[7:0] R/W 0 R/W 0
The Timer/Counter Register gives direct access, both for read and write operations, to the Timer/Counter unit 8-bit counter. Writing to the TCNT0 Register blocks (removes) the Compare Match on the following timer clock. Modifying the counter (TCNT0) while the counter is running, introduces a risk of missing a Compare Match between TCNT0 and the OCR0x Registers. 15.8.4 OCR0A - Output Compare Register A
Bit 0x27 (0x47) Read/Write Initial Value R/W 0 R/W 0 R/W 0 7 6 5 4 3 2 1 0 OCR0A R/W 0 R/W 0 R/W 0 OCR0A[7:0] R/W 0 R/W 0
The Output Compare Register A contains an 8-bit value that is continuously compared with the counter value (TCNT0). A match can be used to generate an Output Compare interrupt, or to generate a waveform output on the OC0A pin. 15.8.5 OCR0B - Output Compare Register B
Bit 0x28 (0x48) Read/Write Initial Value R/W 0 R/W 0 R/W 0 7 6 5 4 3 2 1 0 OCR0B R/W 0 R/W 0 R/W 0 OCR0B[7:0] R/W 0 R/W 0
The Output Compare Register B contains an 8-bit value that is continuously compared with the counter value (TCNT0). A match can be used to generate an Output Compare interrupt, or to generate a waveform output on the OC0B pin.
92
ATmega406
2548E-AVR-07/06
ATmega406
15.8.6 TIMSK0 - Timer/Counter Interrupt Mask Register 0
Bit (0x6E) Read/Write Initial Value 7 - R 0 6 - R 0 5 - R 0 4 - R 0 3 - R 0 2 OCIE0B R/W 0 1 OCIE0A R/W 0 0 TOIE0 R/W 0 TIMSK0
* Bits 7:3 - Res: Reserved Bits These bits are reserved bits in the ATmega406 and will always read as zero. * Bit 2 - OCIE0B: Timer/Counter Output Compare Match B Interrupt Enable When the OCIE0B bit is written to one, and the I-bit in the Status Register is set, the Timer/Counter Compare Match B interrupt is enabled. The corresponding interrupt is executed if a Compare Match in Timer/Counter occurs, i.e., when the OCF0B bit is set in the Timer/Counter Interrupt Flag Register - TIFR0. * Bit 1 - OCIE0A: Timer/Counter0 Output Compare Match A Interrupt Enable When the OCIE0A bit is written to one, and the I-bit in the Status Register is set, the Timer/Counter0 Compare Match A interrupt is enabled. The corresponding interrupt is executed if a Compare Match in Timer/Counter0 occurs, i.e., when the OCF0A bit is set in the Timer/Counter 0 Interrupt Flag Register - TIFR0. * Bit 0 - TOIE0: Timer/Counter0 Overflow Interrupt Enable When the TOIE0 bit is written to one, and the I-bit in the Status Register is set, the Timer/Counter0 Overflow interrupt is enabled. The corresponding interrupt is executed if an overflow in Timer/Counter0 occurs, i.e., when the TOV0 bit is set in the Timer/Counter 0 Interrupt Flag Register - TIFR0.
93
2548E-AVR-07/06
15.8.7
TIFR0 - Timer/Counter 0 Interrupt Flag Register
Bit 0x15 (0x35) Read/Write Initial Value 7 - R 0 6 - R 0 5 - R 0 4 - R 0 3 - R 0 2 OCF0B R/W 0 1 OCF0A R/W 0 0 TOV0 R/W 0 TIFR0
* Bits 7:3 - Res: Reserved Bits These bits are reserved bits in the ATmega406 and will always read as zero. * Bit 2 - OCF0B: Timer/Counter 0 Output Compare B Match Flag The OCF0B bit is set when a Compare Match occurs between the Timer/Counter and the data in OCR0B - Output Compare Register0 B. OCF0B is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, OCF0B is cleared by writing a logic one to the flag. When the I-bit in SREG, OCIE0B (Timer/Counter Compare B Match Interrupt Enable), and OCF0B are set, the Timer/Counter Compare Match Interrupt is executed. * Bit 1 - OCF0A: Timer/Counter 0 Output Compare A Match Flag The OCF0A bit is set when a Compare Match occurs between the Timer/Counter0 and the data in OCR0A - Output Compare Register0. OCF0A is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, OCF0A is cleared by writing a logic one to the flag. When the I-bit in SREG, OCIE0A (Timer/Counter0 Compare Match Interrupt Enable), and OCF0A are set, the Timer/Counter0 Compare Match Interrupt is executed. * Bit 0 - TOV0: Timer/Counter0 Overflow Flag The bit TOV0 is set when an overflow occurs in Timer/Counter0. TOV0 is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, TOV0 is cleared by writing a logic one to the flag. When the SREG I-bit, TOIE0 (Timer/Counter0 Overflow Interrupt Enable), and TOV0 are set, the Timer/Counter0 Overflow interrupt is executed. The setting of this flag is dependent of the WGM02:0 bit setting. Refer to Table 15-8, "Waveform Generation Mode Bit Description" on page 90.
94
ATmega406
2548E-AVR-07/06
ATmega406
16. 16-bit Timer/Counter1
The 16-bit Timer/Counter unit allows accurate program execution timing (event management). The main features are: * One Output Compare Unit * Clear Timer on Compare Match (Auto Reload) * Two Independent Interrupt Sources (TOV1 and OCF1A)
16.1
Overview
Most register and bit references in this document are written in general form. A lower case "n" replaces the Timer/Counter number, and a lower case "x" replaces the output compare unit channel. However, when using the register or bit defines in a program, the precise form must be used, i.e., TCNT1 for accessing Timer/Counter1 counter value and so on. The physical I/O register and bit locations for ATmega406 are listed in the "16-bit Timer/Counter Register Description" on page 100. A simplified block diagram of the 16-bit Timer/Counter is shown in Figure 16-1. CPU accessible I/O registers, including I/O bits and I/O pins, are shown in bold. The PRTIM1 bit in "PRR0 - Power Reduction Register 0" on page 36 must be written to zero to enable TImer/Counter1 module. Figure 16-1. 16-bit Timer/Counter Block Diagram
Count Clear Control Logic clkTn OCFnA (Int.Req.) TOVn (Int.Req.)
Timer/Counter
DATA BUS
TCNTn
=0xFFFF
=
OCRnA TCCRnB
16.1.1
Registers The Timer/Counter (TCNT1) and the Output Compare Register (OCR1A) are both 16-bit registers. Special procedures must be followed when accessing the 16-bit registers. These procedures are described in the section "Accessing 16-bit Registers" on page 96.The Timer/Counter Control Register (TCCR1B) is an 8-bit register an has no CPU access restrictions. Interrupt requests (abbreviated to Int.Req. in the figure) signals are visible in the Timer Interrupt Flag Register (TIFR). Both interrupts are individually masked with the Timer Interrupt Mask Register (TIMSK). TIFR and TIMSK are not shown in the figure. The Timer/Counter is clocked internally via the prescaler. The Clock Select logic block controls which clock source the Timer/Counter uses to increment its value. The Timer/Counter is inactive when no clock source is selected. The output from the clock select logic is referred to as the timer clock (clkT1).
95
2548E-AVR-07/06
The Output Compare Register (OCR1A) is compared with the Timer/Counter value at all time. The compare match event will set the Compare Match Flag (OCF1A) which can be used to generate an output compare interrupt request.
16.2
Accessing 16-bit Registers
The TCNT1 and OCR1A are 16-bit registers that can be accessed by the AVR CPU via the 8-bit data bus. The 16-bit register must be byte accessed using two read or write operations. Each 16-bit timer has a single 8-bit register for temporary storing of the high byte of the 16-bit access. The same temporary register is shared between all 16-bit registers within each 16-bit timer. Accessing the low byte triggers the 16-bit read or write operation. When the low byte of a 16-bit register is written by the CPU, the high byte stored in the temporary register, and the low byte written are both copied into the 16-bit register in the same clock cycle. When the low byte of a 16-bit register is read by the CPU, the high byte of the 16-bit register is copied into the temporary register in the same clock cycle as the low byte is read. Not all 16-bit accesses uses the temporary register for the high byte. Reading the OCR1A 16-bit register does not involve using the temporary register. To do a 16-bit write, the high byte must be written before the low byte. For a 16-bit read, the low byte must be read before the high byte. The following code examples show how to access the 16-bit timer registers assuming that no interrupts updates the temporary register. The same principle can be used directly for accessing the OCR1A Register. Note that when using "C", the compiler handles the 16-bit access. Assembly Code Examples(1)
... ; Set TCNT1 to 0x01FF ldi r17,0x01 ldi r16,0xFF out TCNT1H,r17 out TCNT1L,r16 ; Read TCNT1 into r17:r16 in r16,TCNT1L in r17,TCNT1H ...
C Code Examples(1)
unsigned int i; ... /* Set TCNT1 to 0x01FF */ TCNT1 = 0x1FF; /* Read TCNT1 into i */ i = TCNT1; ... Note: 1. See "About Code Examples" on page 7.
The assembly code example returns the TCNT1 value in the r17:r16 register pair. It is important to notice that accessing 16-bit registers are atomic operations. If an interrupt occurs between the two instructions accessing the 16-bit register, and the interrupt code
96
ATmega406
2548E-AVR-07/06
ATmega406
updates the temporary register by accessing the same or any other of the 16-bit timer registers, then the result of the access outside the interrupt will be corrupted. Therefore, when both the main code and the interrupt code update the temporary register, the main code must disable the interrupts during the 16-bit access. The following code examples show how to do an atomic read of the TCNT1 Register contents. Reading the OCR1A Register can be done using the same principle. Assembly Code Example(1)
TIM16_ReadTCNT1: ; Save global interrupt flag in r18,SREG ; Disable interrupts cli ; Read TCNT1 into r17:r16 in r16,TCNT1L in r17,TCNT1H ; Restore global interrupt flag out SREG,r18 ret
C Code Example(1)
unsigned int TIM16_ReadTCNT1( void ) { unsigned char sreg; unsigned int i; /* Save global interrupt flag */ sreg = SREG; /* Disable interrupts */ _CLI(); /* Read TCNT1 into i */ i = TCNT1; /* Restore global interrupt flag */ SREG = sreg; return i; } Note: 1. See "About Code Examples" on page 7.
The assembly code example returns the TCNT1 value in the r17:r16 register pair.
97
2548E-AVR-07/06
The following code examples show how to do an atomic write of the TCNT1 Register contents. Writing to the OCR1A Register can be done using the same principle. Assembly Code Example(1)
TIM16_WriteTCNT1: ; Save global interrupt flag in r18,SREG ; Disable interrupts cli ; Set TCNT1 to r17:r16 out TCNT1H,r17 out TCNT1L,r16 ; Restore global interrupt flag out SREG,r18 ret
C Code Example(1)
void TIM16_WriteTCNT1( unsigned int i ) { unsigned char sreg; unsigned int i; /* Save global interrupt flag */ sreg = SREG; /* Disable interrupts */ _CLI(); /* Set TCNT1 to i */ TCNT1 = i; /* Restore global interrupt flag */ SREG = sreg; } Note: 1. See "About Code Examples" on page 7.
The assembly code example requires that the r17:r16 register pair contains the value to be written to TCNT1. 16.2.1 Reusing the Temporary High Byte Register If writing to more than one 16-bit register where the high byte is the same for all registers written, then the high byte only needs to be written once. However, note that the same rule of atomic operation described previously also applies in this case.
16.3
Timer/Counter Clock Sources
The Timer/Counter is clocked by an internal clock source. The clock source is selected by the Clock Select logic which is controlled by the Clock Select (CS1[2:0]) bits located in the Timer/Counter Control Register B (TCCR1B). For details on clock sources and prescaler, see "Timer/Counter0 and Timer/Counter1 Prescalers" on page 103.
98
ATmega406
2548E-AVR-07/06
ATmega406
16.4 Counter Unit
The main part of the 16-bit Timer/Counter is the programmable 16-bit bi-directional counter unit. Figure 16-2 shows a block diagram of the counter and its surroundings. Figure 16-2. Counter Unit Block Diagram
DATA BUS (8-bit)
TOVn (Int.Req.) TEMP (8-bit)
Count TCNTnH (8-bit) TCNTnL (8-bit) Clear TCNTn (16-bit Counter) Control Logic clkTn
Signal description (internal signals): Count Clear clkT1 Increment TCNT1 by 1. Clear TCNT1 (set all bits to zero). Timer/Counter clock.
The 16-bit counter is mapped into two 8-bit I/O memory locations: Counter High (TCNT1H) containing the upper eight bits of the counter, and Counter Low (TCNT1L) containing the lower eight bits. The TCNT1H Register can only be indirectly accessed by the CPU. When the CPU does an access to the TCNT1H I/O location, the CPU accesses the high byte temporary register (TEMP). The temporary register is updated with the TCNT1H value when the TCNT1L is read, and TCNT1H is updated with the temporary register value when TCNT1L is written. This allows the CPU to read or write the entire 16-bit counter value within one clock cycle via the 8-bit data bus. It is important to notice that there are special cases of writing to the TCNT1 Register when the counter is counting that will give unpredictable results. The special cases are described in the sections where they are of importance. Depending on the mode of operation used, the counter is cleared or incremented at each Timer Clock (clkT1). The clkT1 is generated from an internal clock source, selected by the Clock Select bits (CS1[2:0]). When no clock source is selected (CS1[2:0] = 0) the timer is stopped. However, the TCNT1 value can be accessed by the CPU, independent of whether clkT1 is present or not. A CPU write overrides (has priority over) all counter clear or count operations.
16.5
Output Compare Unit
The 16-bit comparator continuously compares TCNT1 with the Output Compare Register (OCR1A). If TCNT equals OCR1A the comparator signals a match. A match will set the Output Compare Flag (OCF1A) at the next timer clock cycle. If enabled (OCIE1A = 1), the output compare flag generates an output compare interrupt. The OCF1A flag is automatically cleared when the interrupt is executed. Alternatively the OCF1A flag can be cleared by software by writing a logical one to its I/O bit location.
99
2548E-AVR-07/06
Figure 16-3 shows a block diagram of the output compare unit. The small "n" in the register and bit names indicates the device number (n = 1 for Timer/Counter1), and the "x" indicates output compare unit (A). The elements of the block diagram that are not directly a part of the output compare unit are gray shaded. Figure 16-3. Output Compare Unit, Block Diagram
DATA BUS
(8-bit)
TEMP (8-bit)
OCRnxH (8-bit)
OCRnxL (8-bit)
TCNTnH (8-bit)
TCNTnL (8-bit)
OCRnx (16-bit Register)
TCNTn (16-bit Counter)
= (16-bit Comparator )
OCFnx (Int.Req.)
16.5.1
Compare Match Blocking by TCNT1 Write All CPU writes to the TCNT1 Register will block any compare match that occurs in the next timer clock cycle, even when the timer is stopped. This feature allows OCR1x to be initialized to the same value as TCNT1 without triggering an interrupt when the Timer/Counter clock is enabled. Using the Output Compare Unit Since writing TCNT1 in any mode of operation will block all compare matches for one timer clock cycle, there are risks involved when changing TCNT1 when using any of the output compare channels, independent of whether the Timer/Counter is running or not. If the value written to TCNT1 equals the OCR1x value, the compare match will be missed.
16.5.2
16.6
16.6.1
16-bit Timer/Counter Register Description
TCCR1B - Timer/Counter1 Control Register B
Bit (0x81) Read/Write Initial Value 7 - R/W 0 6 - R/W 0 5 - R 0 4 - R/W 0 3 CTC1 R/W 0 2 CS12 R/W 0 1 CS11 R/W 0 0 CS10 R/W 0 TCCR1B
* Bit 7:4 - Res: Reserved Bits These bits is a reserved bit in the ATmega406 and always reads as zero. * Bit 3 - CTC1: Clear Timer/Counter1 on Compare Match When the CTC1 control bit is set (one), Timer/Counter1 is reset to 0x00 in the CPU clock cycle after a compare match.
100
ATmega406
2548E-AVR-07/06
ATmega406
* Bit 2:0 - CS1[2:0]: Clock Select The three Clock Select bits select the clock source to be used by the Timer/Counter. Table 16-1.
CS12 0 0 0 0 1 1 1 1
CS1[2:0] - Clock Select Bit Description
CS11 0 0 1 1 0 0 1 1 CS10 0 1 0 1 0 1 0 1 Description No clock source (Timer/counter stopped). clkI/O/1 (No prescaling) clkI/O/8 (From prescaler) clkI/O/32 (From prescaler) clkI/O/64 (From prescaler) clkI/O/128 (From prescaler) clkI/O/256 (From prescaler) clkI/O/1024 (From prescaler)
16.6.2
TCNT1H and TCNT1L - Timer/Counter1
Bit (0x85) (0x84) Read/Write Initial Value R/W 0 R/W 0 R/W 0 7 6 5 4 3 2 1 0 TCNT1H TCNT1L R/W 0 R/W 0 R/W 0 TCNT1[15:8] TCNT1[7:0] R/W 0 R/W 0
The two Timer/Counter I/O locations (TCNT1H and TCNT1L, combined TCNT1) give direct access, both for read and for write operations, to the Timer/Counter unit 16-bit counter. To ensure that both the high and low bytes are read and written simultaneously when the CPU accesses these registers, the access is performed using an 8-bit temporary high byte register (TEMP). This temporary register is shared by all the other 16-bit registers. See "Accessing 16-bit Registers" on page 96. Modifying the counter (TCNT1) while the counter is running introduces a risk of missing a compare match between TCNT1 and one of the OCR1x Registers. Writing to the TCNT1 register blocks (removes) the compare match on the following timer clock for all compare units. 16.6.3 OCR1AH and OCR1AL - Output Compare Register 1 A
Bit (0x89) (0x88) Read/Write Initial Value R/W 0 R/W 0 R/W 0 7 6 5 4 3 2 1 0 OCR1AH OCR1AL R/W 0 R/W 0 R/W 0 OCR1A[15:8] OCR1A[7:0] R/W 0 R/W 0
The Output Compare Register contains a 16-bit value that is continuously compared with the counter value (TCNT1). The Output Compare Register is 16-bit in size. To ensure that both the high and low bytes are written simultaneously when the CPU writes to these registers, the access is performed using an 8-bit temporary high byte register (TEMP). This temporary register is shared by all the other 16bit registers. See "Accessing 16-bit Registers" on page 96.
101
2548E-AVR-07/06
16.6.4
TIMSK1 - Timer/Counter Interrupt Mask Register 1
Bit (0x6F) Read/Write Initial Value 7 - R 0 6 - R 0 5 - R 0 4 - R 0 3 - R 0 2 - R 0 1 OCIE1A R/W 0 0 TOIE1 R/W 0 TIMSK1
* Bit 7:2 - Res: Reserved Bits These bits are reserved bits in the ATmega406 and always reads as zero. * Bit 1 - OCIE1A: Timer/Counter1, Output Compare A Match Interrupt Enable When this bit is written to one, and the I-flag in the Status Register is set (interrupts globally enabled), the Timer/Counter1 Output Compare A Match interrupt is enabled. The corresponding Interrupt Vector (see "Reset and Interrupt Handling" on page 14) is executed when the OCF1A flag, located in TIFR1, is set. * Bit 0 - TOIE1: Timer/Counter1, Overflow Interrupt Enable When this bit is written to one, and the I-flag in the Status Register is set (interrupts globally enabled), the Timer/Counter1 overflow interrupt is enabled. The corresponding Interrupt Vector (see "Reset and Interrupt Handling" on page 14) is executed when the TOV1 flag, located in TIFR1, is set. 16.6.5 TIFR1 - Timer/Counter Interrupt Flag Register
Bit 0x16 (0x36) Read/Write Initial Value 7 - R 0 6 - R 0 5 - R 0 4 - R 0 3 - R 0 2 - R 0 1 OCF1A R/W 0 0 TOV1 R/W 0 TIFR1
* Bit 7:2 - Res: Reserved Bits These bits are reserved bits in the ATmega406 and always reads as zero. * Bit 1 - OCF1A: Timer/Counter1, Output Compare A Match Flag This flag is set in the timer clock cycle after the counter (TCNT1) value matches the Output Compare Register A (OCR1A). OCF1A is automatically cleared when the Output compare Match A Interrupt Vector is executed. Alternatively, OCF1A can be cleared by writing a logic one to its bit location. * Bit 0 - TOV1: Timer/Counter1, Overflow Flag TOV1 Flag is set when the Timer overflows. TOV1 is automatically cleared when the Timer/Counter1 Overflow Interrupt Vector is executed. Alternatively, TOV1 can be cleared by writing a logic one to its bit location.
102
ATmega406
2548E-AVR-07/06
ATmega406
17. Timer/Counter0 and Timer/Counter1 Prescalers
Timer/Counter1 and Timer/Counter0 share the same prescaler module, but the Timer/Counters can have different prescaler settings. The description below applies to both Timer/Counter1 and Timer/Counter0.
17.1
Internal Clock Source
The Timer/Counter can be clocked directly by the system clock (by setting the CSn2:0 = 1). This provides the fastest operation, with a maximum Timer/Counter clock frequency equal to system clock frequency (fCLK_I/O). Alternatively, one of the taps from the prescaler can be used as a clock source by setting the CSn2:0. See Table 15-9 on page 92 for Timer/Counter0 settings and Table 16-1 on page 101 for Timer/Counter1 settings. The prescaled clock has a frequency of either fCLK_I/O/8, fCLK_I/O/32, fCLK_I/O/64, fCLK_I/O/128, fCLK_I/O/256, or fCLK_I/O/1024.
17.2
Prescaler Reset
The prescaler is free running, i.e., operates independently of the Clock Select logic of the Timer/Counter, and it is shared by Timer/Counter1 and Timer/Counter0. Since the prescaler is not affected by the Timer/Counter's clock select, the state of the prescaler will have implications for situations where a prescaled clock is used. One example of prescaling artifacts occurs when the timer is enabled and clocked by the prescaler (6 > CSn2:0 > 1). The number of system clock cycles from when the timer is enabled to the first count occurs can be from 1 to N+1 system clock cycles, where N equals the prescaler divisor. It is possible to use the prescaler reset for synchronizing the Timer/Counter to program execution. However, care must be taken if the other Timer/Counter that shares the same prescaler also uses prescaling. A prescaler reset will affect the prescaler period for all Timer/Counters it is connected to.
17.3
External Clock Source
An external clock source applied to the T0 pin can be used as Timer/Counter0 clock (clkT0). The T0 pin is sampled once every system clock cycle by the pin synchronization logic. The synchronized (sampled) signal is then passed through the edge detector. Figure 17-1 shows a functional equivalent block diagram of the T0 synchronization and edge detector logic. The registers are clocked at the positive edge of the internal system clock (clkI/O). The latch is transparent in the high period of the internal system clock. The edge detector generates one clkT0 pulse for each positive (CSn2:0 = 7) or negative (CSn2:0 = 6) edge it detects. Figure 17-1. T1/T0 Pin Sampling
Tn
D LE
Q
D
Q
D
Q
Tn_sync (To Clock Select Logic)
clk I/O
Synchronization Edge Detector
103
2548E-AVR-07/06
The synchronization and edge detector logic introduces a delay of 2.5 to 3.5 system clock cycles from an edge has been applied to the T0 pin to the counter is updated. Enabling and disabling of the clock input must be done when T0 has been stable for at least one system clock cycle, otherwise it is a risk that a false Timer/Counter clock pulse is generated. Each half period of the external clock applied must be longer than one system clock cycle to ensure correct sampling. The external clock must be guaranteed to have less than half the system clock frequency (fExtClk < fclk_I/O/2) given a 50/50% duty cycle. Since the edge detector uses sampling, the maximum frequency of an external clock it can detect is half the sampling frequency (Nyquist sampling theorem). However, due to variation of the system clock frequency and duty cycle caused by Oscillator source (crystal, resonator, and capacitors) tolerances, it is recommended that maximum frequency of an external clock source is less than fclk_I/O/2.5. An external clock source can not be prescaled. Figure 17-2. Prescaler for Timer/Counter0 and Timer/Counter1(1)
PSRSYNC
clk I/O
Clear
CK/32
CK/64
CK/8
T0
Synchronization
clkT1
Note:
1. The synchronization logic on the input pins (T1/T0) is shown in Figure 17-1.
104
ATmega406
2548E-AVR-07/06
CK/1024
clkT0
CK/128
CK/256
ATmega406
17.4
17.4.1
Register Description
GTCCR - General Timer/Counter Control Register
Bit 0x23 (0x43) Read/Write Initial Value 7 TSM R/W 0 6 - R 0 5 - R 0 4 - R 0 3 - R 0 2 - R 0 1 - R 0 0 PSRSYNC R/W 0 GTCCR
* Bit 7 - TSM: Timer/Counter Synchronization Mode Writing the TSM bit to one activates the Timer/Counter Synchronization mode. In this mode, the value that is written to the PSRSYNC bit is kept, hence keeping the corresponding prescaler reset signals asserted. This ensures that the corresponding Timer/Counters are halted and can be configured to the same value without the risk of one of them advancing during configuration. When the TSM bit is written to zero, the PSRSYNC bit is cleared by hardware, and the Timer/Counters start counting simultaneously. * Bit 0 - PSRSYNC: Prescaler Reset When this bit is one, Timer/Counter1 and Timer/Counter0 prescaler will be Reset. This bit is normally cleared immediately by hardware, except if the TSM bit is set. Note that Timer/Counter1 and Timer/Counter0 share the same prescaler and a reset of this prescaler will affect both timers.
105
2548E-AVR-07/06
18. Coulomb Counter - Dedicated Fuel Gauging Sigma-delta ADC
18.1 Features
* * * * * * * * * * *
Sampled System Coulomb Counter Low Power Sigma-Delta ADC Optimized for Coulomb Counting Instantaneous Current Output with 3.9 ms Conversion Time Accumulate Current Output with Programmable Conversion Time: 125/250/500/1000 ms Input voltage Range Larger than 0.15V, Allowing Measurement of more than 30A @ 5 m 13-bit Resolution (including sign) corresponding to 53.7 V (10.7 mA @ 5 m) for Instantaneous Current Output 18-bit Resolution (including sign) corresponding to 1.68 V (0.335 A @ 5 m) for Accumulate Current Output Input Offset Less than 10 V for the ADC Interrupt on Instantaneous Current Conversion Complete Interrupt on Accumulate Current Conversion Complete Interrupt on Regular Current with Programmable Compare Level and Programmable Sampling Interval: 250/500/1000/2000 ms
ATmega406 features a dedicated Sigma-Delta ADC (CC-ADC) optimized for Coulomb Counting to sample the charge or discharge current flowing through the external sense resistor RSENSE. Two different output values are provided, Instantaneous Current and Accumulate Current. The Instantaneous Current Output has a short conversion time at the cost of lower resolution. The Accumulate Current Output provides a highly accurate current measurement for Coulomb Counting. The sampling Coulomb Counter provides a highly accurate and flexible solution. Accuracy can easily be traded against conversion time. It also provides Regular Current detection. This allows ultra-low power operation in Power-save mode when small charge or discharge currents are flowing. Figure 18-1. Coulomb Counter Block Diagram
8-BIT DATABUS
Regular Current IRQ Level
INSTANTANEOUS CURRENT
Current Comparator IRQ
PI
Control & Status Register
IRQ Sigma Delta modulator Decimation Decimation
ACCUMULATE CURRENT
IRQ
R SENSE NI
106
ATmega406
2548E-AVR-07/06
ATmega406
18.2 Operation
When enabled, the CC-ADC continuously measures the voltage over the external sense resistor RSENSE. The Instantaneous Current conversion time is fixed to 3.9 ms (typical value) allowing the output value to closely follow the input. After each Instantaneous Current conversion an interrupt is generate if the interrupt is enabled. Data from conversion will be updated in the Instantaneous Current registers - CADICL and CADICH simultaneously as the interrupt is given. To avoid losing conversion data, both the low and high byte must be read within a 3,9 ms timing window after the corresponding interrupt is given. When the low byte register is read, updating of the Instantaneous Current registers and interrupts will be stopped until the high byte is read. Figure 18-2 shows an Instantaneous Current conversion diagram, where DATA4 will be lost because DATA3 reading is not completed within the limited period.
Figure 18-2. Instantaneous Current Conversion
Enable
~12 ms settling 3.9 ms 3.9 ms 7.8 ms
Instantaneous Interrupt
Instantaneous Data
Setting of Digital Filters
DATA1
DATA2
DATA 3
DATA5
Read low byte
Read high byte
The Accumulate Current output is a high-resolution, high accuracy output with programmable conversion time selected by the CADAS bits in CADCSRA. The converted value is an accurate measurement of the average current flow during one conversion period. The CC-ADC generates an interrupt each time a new Accumulate Current conversion has finished if the interrupt is enabled. Data from conversion will be updated in the Accumulation Current registers - CADAC0, CADAC1, CADAC2 and CADAC3 simultaneously as the interrupt is given. To avoid losing conversion data, all bytes must be read within the selected conversion period. When the lower byte registers are read, updating of the Accumulation Current registers and interrupts will be stopped until the highest byte is read. Figure 18-3 on page 108 shows an Accumulation Current conversion example, where DATA4 will be lost because DATA3 reading is not completed within the limited period.
107
2548E-AVR-07/06
Figure 18-3. Accumulation Current Conversion
Enable
125, 250, 500, or 1000 ms 125, 250, 500, or 1000 ms 250, 500, 1000, or 2000 ms
Accumulation Interrupt
Accumulation Data
Setting of Digital Filters
DATA1
DATA2
DATA 3
DATA5
Read byte 1
Read byte 2
Read byte 3
Read byte 4
While the CC-ADC is converting, the CPU can enter sleep mode and wait for an interrupt from the Accumulate Current conversion. After adding the new Accumulate Current value for Coulomb Counting, the CPU can go back to sleep again. This reduces the CPU workload, and allows more time spent in low power modes, reducing power consumption. The CC-ADC can generate an interrupt if the result of an Instantaneous Current conversion is greater than a programmable threshold. This allows the detection of a Regular Current condition. This function is available in Active mode and all sleep modes except Power-down and Power-off mode. This allows an ultra-low power operation in Power-save, where the CC-ADC can be configured to enter a Regular Current detection mode with a programmable current sampling interval. By setting the CADSE bit in CADCSRA, the Coulomb Counter will repeatedly do one Instantaneous Current conversion, before it is being turned off for a timing interval specified by the CADSI bits in CADCSRA. This allows operating the Regular Current detection while keeping the Coulomb Counter off most of the time. The Coulomb Counter is halted in Power-down mode. In this mode, time measurements and the battery self-discharge characteristics should be used to estimate the charge flow. When waking up from Power-down mode, the CC-ADC will automatically resume continuous operation. The CC-ADC is enabled by setting the CC-ADC Enable bit, CADEN, in CADCSRA. Note that the bandgap voltage reference must be enabled separately, see "BGCCR - Bandgap Calibration C Register" on page 123. The CC-ADC will not consume power when CADEN is cleared. It is therefore recommended to switch off the CC-ADC whenever the Coulomb Counter or Regular Current Detection functions are not used. The CC-ADC is automatically disabled in Power-down and Power-off mode. After the CC-ADC is enabled, either by setting the CADEN bit or leaving Power-down with CADEN already set, the first four conversions do not contain useful data and should be ignored. This also applies after clearing the CADSE bit. In-system offset voltage for the CC-ADC is typically in the range 0 - 100 V. To compensate for this offset error, a CC-ADC offset value should be stored in EEPROM and subtracted from each Accumulate Current conversions before the resulting value is added for Coloumb Counting. The CC-ADC offset value can be found by performing a CC-ADC conversion at typical temperature with zero current flowing through RSENSE. When the battery is not used or the current level stays very low for a long time, it is recommended to estimate the charge flow instead of using the CC-ADC for Coloumb Counting. The
108
ATmega406
2548E-AVR-07/06
ATmega406
charge flow estimation should be based on the self-discharge rate of the battery and the standby current of the battery system. 18.2.1 CADCSRA - CC-ADC Control and Status Register A
Bit (0xE4) Read/Write Initial Value 7
CADEN
6
-
5
CADUB
4
CADAS1
3
CADAS0
2
CADSI1
1
CADSI0
0
CADSE CADCSRA
R/W 0
R 0
R 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
* Bit 7 - CADEN: CC-ADC Enable When the CADEN bit is cleared (zero), the CC-ADC is disabled, and any ongoing conversions will be terminated. When the CADEN bit is set (one), the CC-ADC will continuously measure the voltage drop over the external sense resistor RSENSE. In Power-off, the CC-ADC is always disabled. Note that the bandgap voltage reference must be enabled separately, see "BGCCR - Bandgap Calibration C Register" on page 123. * Bit 6 - Res: Reserved This bit is reserved bit in the ATmega406 and will always read as zero. * Bit 5 - CADUB: CC-ADC Update Busy The CC-ADC operates in a different clock domain than the CPU. Whenever a new value is written to CADCSRA, CADRCC or CADRDC, this value must be synchronized to the CC-ADC clock domain. Subsequent writes to these registers will be blocked during this synchronization. Synchronization of one of the registers, will block updating of all the others. The CADUB bit will be read as one while any of these registers is being synchronized, and will be read as zero when neither register is being synchronized. * Bits 4:3 - CADAS1:0: CC-ADC Accumulate Current Select The CADAS bits select the conversion time for the Accumulate Current output as shown in Table 18-1. Table 18-1. CC-ADC Accumulate Current Conversion Time
CC-ADC Accumulate Current Conversion Time 125 ms 250 ms 500 ms 1s
CADAS1:0 00 01 10 11
109
2548E-AVR-07/06
* Bits 2:1 - CADSI1:0: CC-ADC Current Sampling Interval The CADSI bits determine the current sampling interval for the Regular Current detection as shown in Table 18-2. The current sampling interval is only used if the CADSE bit is set. Table 18-2. CC-ADC Regular Current Sampling Interval
CC-ADC Regular Current Sampling Interval(1)(2) 250 ms (+ sampling time) 500 ms (+ sampling time) 1 s (+ sampling time) 2 s (+ sampling time)
CADSI1:0 00 01 10 11 Notes:
1. The actual value of depends on the actual frequency of the "Slow RC Oscillator" on page 27. See "Electrical Characteristics" on page 225. 2. Sampling time ~ 12 ms.
* Bit 0 - CADSE: CC-ADC Current Sampling Enable When the CADSE bit is written to one, the ongoing CC-ADC conversion is aborted, and the CCADC enters Regular Current detection mode. 18.2.2 CADCSRB - CC-ADC Control and Status Register B
Bit (0xE5) Read/Write Initial Value 7
-
6
CADACIE
5
CADRCIE
4
CADICIE
3
-
2
CADACIF
1
CADRCIF
0
CADICIF CADCSRB
R 0
R/W 0
R/W 0
R/W 0
R 0
R/W 0
R/W 0
R/W 0
* Bits 7, 3 - Res: Reserved These bits are reserved bits in the ATmega406 and will always read as zero. * Bit 6 - CADACIE: CC-ADC Accumulate Current Interrupt Enable When the CADACIE bit is set (one), and the I-bit in the Status Register is set (one), the CC-ADC Accumulate Current Interrupt is enabled. * Bit 5 - CADRCIE: CC-ADC Regular Current Interrupt Enable When the CADRCIE bit is set (one), and the I-bit in the Status Register is set (one), the CC-ADC Regular Current Interrupt is enabled. * Bit 4 - CADICIE: CC-ADC Instantaneous Current Interrupt Enable When the CADICIE bit is set (one), and the I-bit in the Status Register is set (one), the CC-ADC Instantaneous Current Interrupt is enabled. * Bit 2 - CADACIF: CC-ADC Accumulate Current Interrupt Flag The CADACIF bit is set (one) after the Accumulate Current conversion has completed. The CCADC Accumulate Current Interrupt is executed if the CADACIE bit and the I-bit in SREG are set (one). CADACIF is cleared by hardware when executing the corresponding Interrupt Handling Vector. Alternatively, CADACIF is cleared by writing a logic one to the flag. * Bit 1 - CADRCIF: CC-ADC Regular Current Interrupt Flag
110
ATmega406
2548E-AVR-07/06
ATmega406
The CADRCIF bit is set (one) when the absolute value of the result of the last CC-ADC conversion is greater than, or equal to, the compare values set by the CC-ADC Regular Charge/Discharge Current Level Registers. A positive value is compared to the Regular Charge Current Level, and a negative value is compared to the Regular Discharge Current Level. The CC-ADC Regular Current Interrupt is executed if the CADRCIE bit and the I-bit in SREG are set (one). CADRCIF is cleared by hardware when executing the corresponding Interrupt Handling vector. Alternatively, CADRCIF is cleared by writing a logic one to the flag. * Bit 0 - CADICIF: CC-ADC Instantaneous Current Interrupt Flag The CADICIF bit is set (one) when a CC-ADC Instantaneous Current conversion is completed. The CC-ADC Instantaneous Current Interrupt is executed if the CADICIE bit and the I-bit in SREG are set (one). CADICIF is cleared by hardware when executing the corresponding Interrupt Handling vector. Alternatively, CADICIF is cleared by writing a logic one to the flag. 18.2.3 CADICH and CADICL - CC-ADC Instantaneous Current
Bit (0xE9) (0xE8) Bit Read/Write 7 R R Initial Value 0 0 6 R R 0 0 5 R R 0 0 15 14 13 12 11 10 9 8 CADICH CADICL 2 R R 0 0 1 R R 0 0 0 R R 0 0
CADIC[15:8] CADIC[7:0] 4 R R 0 0 3 R R 0 0
When a CC-ADC Instantaneous Current conversion is complete, the result is found in these two registers. CADIC15:0 represents the converted result in 2's complement format, sign extended to 16 bits. When CADICL is read, the CC-ADC Instantaneous Current register is not updated until CADCH is read. Reading the registers in the sequence CADICL, CADICH will ensure that consistent values are read. 18.2.4 CADAC3, CADAC2, CADAC1 and CADAC0 - CC-ADC Accumulate Current
Bit 31 23 15 7 (0xE3) (0xE2) (0xE1) (0xE0) Read/Write R R R Initial Value 0 0 0 R R R 0 0 0 R R R 0 0 0 30 22 14 6 29 21 13 5 28 20 12 4 27 19 11 3 26 18 10 2 25 17 9 1 24 16 8 0 CADAC3 CADAC2 CADAC1 CADAC0 R R R 0 0 0 R R R 0 0 0 R R R 0 0 0
CADAC[31:24] CADAC[23:16] CADAC[15:8] CADAC[7:0] R R R 0 0 0 R R R 0 0 0
The CADAC3, CADAC2, CADAC1 and CADAC0 Registers contain the Accumulate Current measurements in 2's complement format, sign extended to 32 bits.
111
2548E-AVR-07/06
When CADAC0 is read, the CC-ADC Accumulate Current register is not updated until CADAC3 is read. Reading the registers in the sequence CADAC0, CADAC1, CADAC2, CADAC3 will ensure that consistent values are read. 18.2.5 CADRCC - CC-ADC Regular Charge Current
Bit (0xE6) Read/Write Initial Value R/W 0 R/W 0 R/W 0 7 6 5 4 3 2 1 0
CADRCC
CADRCC[7:0]
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
The CC-ADC Regular Charge Current Register determines the threshold level for the Regular Charge Current detection. When the result of a CC-ADC Instantaneous Current conversion is positive with a value greater than, or equal to, the Regular Charge Current level, the CC-ADC Regular Current Interrupt Flag is set. The value in this register is specified in 2's complement format, and it defines the eight least significant bits of the Regular Charge Current level. The most significant bits of the Regular Charge Current level are always zero. The programmable range for the Regular Charge Current level is given in Table 18-3. Table 18-3. Programmable Range for the Regular Charge Current Level
Minimum Voltage (V) Current (mA) RSENSE = 5 m RSENSE = 7 m 0 0 0 Maximum 13700 2740 1957 Step Size 53.7 10.7 7.7
The CC-ADC Regular Charge Current Register does not affect the setting of the CC-ADC Conversion Complete Interrupt Flag. 18.2.6 CADRDC - CC-ADC Regular Discharge Current
Bit (0xE7) Read/Write Initial Value R/W 0 R/W 0 R/W 0 7 6 5 4
CADRDC[7:0]
3
2
1
0
CADRDC
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
The CC-ADC Regular Discharge Current Register determines the threshold level for the Regular Discharge Current detection. When the result of a CC-ADC Instantaneous Current conversion is negative with an absolute value greater than, or equal to, the Regular Discharge Current level, the CC-ADC Regular Current Interrupt Flag is set. The value in this register is specified in 2's complement format, and it defines the eight least significant bits of the Regular Discharge Current level. The most significant bits of the Regular
112
ATmega406
2548E-AVR-07/06
ATmega406
Charge Current level are always one. The programmable range for the Regular Discharge Current level is given in Table 18-4. Table 18-4. Programmable Range for the Regular Discharge Current Level
Minimum Voltage (V) Current (mA) RSENSE = 5 m RSENSE = 7 m 0 0 0 Maximum 13700 2740 1957 Step Size 53.7 10.7 7.7
The CC-ADC Regular Discharge Current Register does not affect the setting of the CC-ADC Conversion Complete Interrupt Flag.
113
2548E-AVR-07/06
19. Voltage Regulator
19.1 Features
* Linear Regulation. * Operating Voltage Range 4.0 - 25V. * Fixed Output Voltage at 3.3V. ATmega406 is supplied by the VFET terminal. Operating voltage range at the VFET terminal is 4.0 - 25V. The Internal Voltage Regulator regulates this voltage down to 3.3V, which is a suitable supply voltage for the internal logic, I/O lines, and analog circuitry. An external decoupling capacitor of 1 F or larger is required for stable operation of the Voltage Regulator. A larger capacitor will allow larger load currents and increase start-up time. The block diagram of the Voltage Regulator is shown in Figure 19-1. Figure 19-1. Voltage Regulator Block Diagram
VFET Voltage Regulator
RN PVT PV1 Regulator Control LDO_ON LDO Regulator VREG
Creg > 1 uF RP
POWER_OFF
Power Distributor
Rsense Digital Supply Analog Supply
19.2
Operation
The Regulator will operate in all sleep modes, including Power-off. In this mode the regulator will automatically reduce the ATmega406's power consumption by turning off supply for all peripheral modules, allowing only the Charger Detect module and the Voltage Regulator itself to operate. The Regulator will automatically ensure that it has stable work conditions before allowing itself to start regulating the VFET terminal. If the voltage at the VFET pin is below the Regulator-on Threshold voltage, VROT, the LDO will be switched off. Powering-up the regulator is either done from the battery side when the smart battery controller is assembled with the battery pack and there is no charger present, or from the charger side when a deep discharge has occurred (0V charging). When powering- up with a charger present, the voltage between the VFET and the PVT pin must be above a Charge-Threshold voltage, VCHT.
114
ATmega406
2548E-AVR-07/06
ATmega406
When powering-up without a charger present, the voltage on Cell1, VPV1, must be above the Cell1-Threshold voltage, VPV1T. After powering-up the regulator the chip will enter Power-off sleep mode (lowest power consumption). Until a charger is detected, the chip will stay in this mode. For details on Charger Detect, see "Power-on Reset and Charger Connect" on page 40. Table 30-2 on page 230 shows the characteristics for powering-up the LDO.
115
2548E-AVR-07/06
20. Voltage ADC - 10-channel General Purpose 12-bit Sigma-Delta ADC
20.1 Features
* * * * * * * *
12-bit Resolution 1 LSB Accuracy 519s Conversion Time Four Differential Input Channels for Cell Voltage Measurements Six Single Ended Input Channels 0 to 0.9 x VREF Input Voltage Range 0.2x Pre-scaling of Cell Voltages and VREG Interrupt on V-ADC Conversion Complete
The ATmega406 features a 12-bit Sigma-Delta ADC. Automatic offset cancellation technique reduces the input offset voltage to less than 0.5 mV. The Voltage ADC (V-ADC) is connected to ten different sources through the Input Multiplexer. There are four differential channels for Cell Voltage measurements. These channels are scaled 0.2x to comply with the Full Scale range of the V-ADC. In addition there are six single ended channels referenced to SGND. One channel is for measuring the internal temperature sensor VPTAT and five channels for measuring the ADC input pins at Port A. ADC3:0 are not scaled, meaning that full-scale reading corresponds to 1.1 V. ADC4 is scaled by 0.2x, meaning that fullscale reading corresponds to 5.5 V. The ADC4 input can be used to measure the voltage at the PA4 pin when this pin is used to supply an external thermistor, see Figure 29-1 on page 223. To obtain a total absolute accuracy better than 0.25% for the cell voltage measurements, calibration registers for the individual cell voltage gain in the analog front-end is provided. A factory calibration value is stored in the signature row, see Section 27.7.10 "Reading the Signature Row from Software" on page 189. The V-ADC conversion of a cell voltage must be scaled with the corresponding calibration value by software to correct for gain error in the analog front-end. The PRVADC bit in "PRR0 - Power Reduction Register 0" on page 36 must be written to zero to enable V-ADC module.
116
ATmega406
2548E-AVR-07/06
ATmega406
Figure 20-1. Voltage ADC Block Schematic
V-ADC CONVERSION COMPLETE IRQ
8-BIT DATA BUS
VADCCIE
V-ADC CONTROL AND STATUS REG (VADCSR) V-ADC DATA REGISTER (VADCL/ADCH)
ADC3 ADC2 ADC1 ADC0 VTEMP
V-ADC MULTIPLEXER SEL. REG (VADMUX)
V-ADC CONTROL
ADC4 PV4 PV3 PV2 PV1 NV
INPUT MUX
12-BIT SIGMA-DELTA ADC
VREF
Note: The shaded signals are scaled by 0.2, other signals are scaled by 1.0
SGND
20.2
Operation
To enable V-ADC conversions, the V-ADC Enable bit, VADEN, in V-ADC Control and Status Register - VADCSR must be set. If this bit is cleared, the V-ADC will be switched off, and any ongoing conversions will be terminated. The V-ADC is automatically halted in Power-save, Power-down and Power-off mode. Note that the bandgap voltage reference must be enabled and disabled separately, see "BGCCR - Bandgap Calibration C Register" on page 123. Figure 20-2. Voltage ADC Conversion Diagram
519 us Start Conversion
Interrupt
Conversion Result
OLD DATA
INVALID DATA
VA L I D
VADCCIF
D ATA
INVALID DATA
To perform a V-ADC conversion, the analog input channel must first be selected by writing to the VADMUX bits in VADMUX. When a logical one is written to the V-ADC Start Conversion bit VADSC, a conversion of the selected channel will start. The VADSC bit stays high as long as the conversion is in progress and will be cleared by hardware when the conversion is completed. If a different data channel is selected while a conversion is in progress, the ADC will finish the current conversion before performing the channel change. When a conversion is finished the V-
117
2548E-AVR-07/06
ADC Conversion Complete Interrupt Flag - VADCCIF is set. One 12-bit conversion takes 519 s to complete from the start bit is set to the interrupt flag is set. To ensure that correct data is read, both high and low byte data registers should be read before starting a new conversion.
20.3
20.3.1
Register Description
VADMUX - V-ADC Multiplexer Selection Register
Bit (0x7C) Read/Write Initial Value 7
-
6
-
5
-
4
-
3
VADMUX3
2
VADMUX2
1
VADMUX1
0
VADMUX0 VADMUX
R 0
R 0
R 0
R 0
R/W 0
R/W 0
R/W 0
R/W 0
* Bit 7:4 - RES: Reserved Bits These bits are reserved bits in the ATmega406 and will always read as zero. * Bit 3:0 - VADMUX3:0: V-ADC Channel Selection Bits The VADMUX bits determine the V-ADC channel selection. See Table 20-1 on page 118. Table 20-1. VADMUX channel selection
Channel Selected CELL 1 CELL 2 CELL 3 CELL 4 ADC4 VTEMP ADC0 ADC1 ADC2 ADC3 Scale 0.2 0.2 0.2 0.2 0.2 1.0 1.0 1.0 1.0 1.0
VADMUX3:0 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010
20.3.2
VADCSR - V-ADC Control and Status Register
Bit (0x7A) Read/Write Initial Value 7
-
6
-
5
-
4
-
3
VADEN
2
VADSC
1
VADCCIF
0
VADCCIE VADCSR
R 0
R 0
R 0
R 0
R/W 0
R/W 0
R/W 0
R/W 0
* Bit 7:4 - RES: Reserved Bits These bits are reserved bits in the ATmega406 and will always read as zero. * Bit 3 - VADEN: V-ADC Enable Writing this bit to one enables V-ADC conversion. By writing it to zero, the V-ADC is turned off. Turning the V-ADC off while a conversion is in progress will terminate this conversion. Note that the bandgap voltage reference must be enabled separately, see "BGCCR - Bandgap Calibration C Register" on page 123.
118
ATmega406
2548E-AVR-07/06
ATmega406
* Bit 2 - VADSC: Voltage ADC Start Conversion Write this bit to one to start a new conversion of the selected channel. VADSC will read as one as long as the conversion is not finished. When the conversion is complete, it returns to zero. Writing zero to this bit has no effect. VADSC will automatically be cleared when the VADEN bit is written to zero. * Bit 1 - VADCCIF: V-ADC Conversion Complete Interrupt Flag This bit is set when a V-ADC conversion completes and the data registers are updated. The VADC Conversion Complete Interrupt is executed if the VADCCIE bit and the I-bit in SREG are set. VADCCIF is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, VADCCIF is cleared by writing a logical one to the flag. Beware that if doing a Read-Modify-Write on VADCSR, a pending interrupt can be disabled. * Bit 0 - VADCCIE: V-ADC Conversion Complete Interrupt Enable When this bit is written to one and the I-bit in SREG is set, the V-ADC Conversion Complete Interrupt is activated.
20.3.3
VADCL and VADCH - The V-ADC Data Register
Bit (0x79) (0x78) 7 Read/Write R R Initial Value 0 0 6 R R 0 0 5 R R 0 0 4 R R 0 0 15 - 14 - 13 - 12 - VADC[7:0] 3 R R 0 0 2 R R 0 0 1 R R 0 0 0 R R 0 0 11 10 VADC[11:8] 9 8 VADCH VADCL
When a V-ADC conversion is complete, the result is found in these two registers. To ensure that correct data is read, the data registers must be read before starting a new conversion. * VADC11:0: V-ADC Conversion Result These bits represent the result from the conversion. To obtain the best absolute accuracy for the cell voltage measurements, gain and offset compensation is required. Factory calibration values are stored in the device signature row, refer to section "Reading the Signature Row from Software" on page 189 for details. The cell voltage in mV is given by:
cell n result cell n gain calibration word Cell n voltage ( mV ) = --------------------------------------------------------------------------------------------------- - cell n offset calibration word TBD
When performing a Vtemp conversion, the result must be adjusted by the factory calibration value stored in the signature row, refer to section "Reading the Signature Row from Software" on page 189 for details. The absolute temperature in Kelvin is given by:
V temp result VPTAT calibration word T(K) = ----------------------------------------------------------------------------------------------TBD
119
2548E-AVR-07/06
20.3.4
DIDR0 - Digital Input Disable Register 0
Bit (0x7E) Read/Write Initial Value 7 - R 0 6 - R 0 5 - R 0 4 - R 0 3 VADC3D R/W 0 2 VADC2D R/W 0 1 VADC1D R/W 0 0 VADC0D R/W 0 DIDR0
* Bits 7:4 - Res: Reserved Bits These bits are reserved for future use. To ensure compatibility with future devices, these bits must be written to zero when DIDR0 is written. * Bit 3:0 - VADC3D:VADC0D: V-ADC3:0 Digital Input Disable When this bit is written logic one, the digital input buffer on the corresponding V-ADC pin is disabled. The corresponding PIN Register bit will always read as zero when this bit is set. When an analog signal is applied to the VADC3:0 pin and the digital input from this pin is not needed, this bit should be written logic one to reduce power consumption in the digital input buffer.
120
ATmega406
2548E-AVR-07/06
ATmega406
21. Voltage Reference and Temperature Sensor
21.1 Features
* * * * * *
Accurate Voltage Reference of 1.100V 0.1% Accuracy After Calibration (2 mV Calibration Steps) Temperature Drift Less than 80 ppm/C after Calibration Alternate Low Power Voltage Reference for Voltage Regulator Internal Temperature Sensor Possibility for Runtime Compensation of Temperature Drift in Both Voltage Reference and Onchip Oscillators * External Decoupling for Optimum Noise Performance * Low Power Consumption
A low power band-gap reference provides ATmega406 with an accurate On-chip voltage reference V REF of 1.100V. This reference voltage is used as reference for the On-chip Voltage Regulator, the V-ADC and the CC-ADC. The reference to the ADCs uses a buffer with external decoupling capacitor to enable excellent noise performance with minimum power consumption. The reference voltage VREF_P/VREF_N to the CC-ADC is scaled to match the full scale requirement at the current sense input pins. This configuration also enables concurrent operation of both V-ADC and CC-ADC. To guaranty ultra low temperature drift after factory calibration, ATmega406 features a two-step calibration algorithm. The first step is performed at 85C and the second at room temperature. By default, Atmel factory calibration is performed at 85C, and the result is stored in Flash. The customer can easily implement the second calibration step in their test flow. This requires an accurate input voltage and a stable room temperature. Temperature drift after this calibration is guarantied by design and characterization to be less than 80 ppm/C from 0C to 60C and 100 ppm/C from 0C to 85C. The BG Calibration C Register can also be altered runtime to implement temperature compensation in software. Very high accuracy for any temperature inside the temperature range can thus be achieved at the cost of extra calibration steps. A lower power, less accurate voltage reference source exists. This voltage reference source is chosen as reference for the voltage regulator whenever the band-gap voltage reference is disabled. This voltage reference source is not available for the V-ADC and CC-ADC. ATmega406 has an On-chip temperature sensor for monitoring the die temperature. A voltage Proportional-To-Absolute-Temperature, VPTAT, is generated in the voltage reference circuit and connected to the multiplexer at the V-ADC input. This temperature sensor can be used for runtime compensation of temperature drift in both the voltage reference and the On-chip Oscillator. To get the absolute temperature in degrees Kelvin, the measured VPTAT voltage must be scaled with the VPTAT factory calibration value stored in the signature row. See "Reading the Signature Row from Software" on page 189 for details.
121
2548E-AVR-07/06
Figure 21-1. Reference Circuitry
1.1V VREF
BG Reference VPTAT VREF_P 0.22V VREF_N CREF
VREF_GND
21.2
Writing to Bandgap Calibration Registers
When the calibration registers are changed it will affect both the Voltage Regulator output and BOD-level. The BOD will react quickly to new detection levels, while the regulator will adjust the voltage more slowly, depending on the size of the external decoupling capacitor. To avoid that a BOD-reset is issued when calibration is done, it is recommended to change the values of the BGCC and BGCR bits stepwise, with a step size of 1, and with a hold-off time between each step. The hold-off time depends on the size of the voltage regulators external decoupling capacitor. For details, see Table 21-1.
Table 21-1.
Hold-off Times depending on CREG.
Hold-off Time BGCCR 1.2 s 2.4 s 3.6 s 4.8 s 6.0 s 7.2 s 8.4 s 9.6 s 10.8 s 12.0 s Hold-off Time BGCRR 3.0 s 6.0 s 9.0 s 12.0 s 15.0 s 18.0 s 21.0 s 24.0 s 27.0 s 30.0 s 1 F 2 F 3 F 4 F 5 F 6 F 7 F 8 F 9 F 10 F
Regulator Cap
122
ATmega406
2548E-AVR-07/06
ATmega406
21.3
21.3.1
Register Description for Voltage Reference and Temperature Sensor
BGCCR - Bandgap Calibration C Register
Bit (0xD0) Read/Write Initial Value 7 BGEN R 0 6 - R 0 5 BGCC5 R/W 0 4 BGCC4 R/W 0 3 BGCC3 R/W 0 2 BGCC2 R/W 0 1 BGCC1 R/W 0 0 BGCC0 R/W 0 BGCCR
* Bit 7 - BGEN This bit is not available from revision E and on of the ATmega406. A complete description is found in the revision A of this document. * Bit 6 - Res: Reserved Bit This bit is reserved for future use. * Bit 5:0 - BGCC5:0: BG Calibration of PTAT Current These bits are used for trimming of the nominal value of the bandgap reference voltage. These bits are binary coded. Minimum VREF: 000000, maximum VREF: 111111. Step size approximately 2 mV. 21.3.2 BGCRR - Bandgap Calibration R Register
Bit (0xD1) Read/Write Initial Value 7 BGCR7 R/W 0 6 BGCR6 R/W 0 5 BGCR5 R/W 0 4 BGCR4 R/W 0 3 BGCR3 R/W 0 2 BGCR2 R/W 0 1 BGCR1 R/W 0 0 BGCR0 R/W 0 BGCRR
* Bit 7:0 - BGCR7:0: BG Calibration of Resistor ladder These bits are used for temperature gradient adjustment of the bandgap reference. Figure 21-2 illustrates VREF as a function of temperature. VREF has a positive temperature coefficient at low temperatures and negative temperature coefficient at high temperatures. Depending on the process variations, the top of the VREF curve may be located at higher or lower temperatures. To minimize the temperature drift in the temperature range of interest, BGCRR is used to adjust the top of the curve towards the centre of the temperature range of interest. The BGCRR bits are temperature coded resulting in 9 possible settings: 00000000, 00000001, 00000011, 00000111, ... , 11111111. The value 00000000 shifts the top of the VREF curve to the highest possible temperature, and the value 11111111 shifts the top of the VREF curve to the lowest possible temperature.
123
2548E-AVR-07/06
Figure 21-2. Illustration of VREF as a function of temperature.
1.5 BGCRR is used to move the top of the VREF curve to the center of the tempearture range of
interest.
Temperature range of interest 1
VREF [V]
0.5
0 -40
-20
0
20
40
60
80
100
Temperature [o C]
124
ATmega406
2548E-AVR-07/06
ATmega406
22. Battery Protection
22.1 Features
* * * * * *
Deep Under-voltage Protection Charge Over-current Protection Discharge Over-current Protection Short-circuit Protection Programmable and Lockable Detection Levels and Reaction Times Autonomous Operation Independent of CPU
If the voltage at the VFET pin falls below the programmable Deep Under-voltage detection level, C-FET, PC-FET, and D-FET are disabled and the chip is set in Power-off mode to reduce power consumption to a minimum. The Current Battery Protection circuitry (CBP) monitors the charge and discharge current and disables C-FET, PC-FET, and D-FET if an over-current or short-circuit condition is detected. There are three different programmable detection levels: Discharge Over-current Detection Level, Charge Over-current Detection Level and Short-circuit Detection Level. The external filter at the PI/NI input pins will cause too large delay for short-circuit detection. Therefore the separate PPI/NNI inputs are used for Current Battery Protection. There are two different programmable delays for activating Current Battery Protection: Short-circuit Reaction Time and Over-current Reaction Time. After Current Battery Protection has been activated, the application software must re-enable the FETs. The Battery Protection hardware provides a hold-off time of 1 second before software can re-enable the discharge FET. This provides safety in case the application software should unintentionally re-enable the discharge FET too early. The activation of a protection also issues an interrupt to the CPU. The battery protection interrupts can be individually enabled and disabled by the CPU. The effect of the various battery protection types is given in Table 22-1. Table 22-1. Effect of Battery Protection Types
Interrupt Requests CPU Reset on exit Entry and exit Entry and exit Entry and exit C-FET Disabled Disabled Disabled Disabled D-FET Disabled Disabled Disabled Disabled PC-FET Disabled Disabled Disabled Disabled Cell Balancing FETs Disabled Operational Operational Operational MCU Power-off Operational Operational Operational
Battery Protection Type Deep Under-voltage Detected Discharge Over-current Protection Charge Over-current Protection Short-circuit Protection
In order to reduce power consumption, both Short-circuit and Discharge Over-current Protection are automatically deactivated when the D-FET is disabled. The Charge Over-current Protection is disabled when both the C-FET and the PC-FET are disabled. Note however that Charge Overcurrent Protection is never automatically disabled when any of the C-FET or PC-FETs are controlled by PWM.
125
2548E-AVR-07/06
22.2
Deep Under-voltage Protection
The Deep Under-voltage Protection ensures that the battery cells will not be discharged deeper than the programmable Deep Under-voltage detection level. If the voltage at the VFET pin is below this level for a time longer than the programmable delay time, C-FET, PC-FET and D-FET are automatically switched off and the chip enters Power-off mode. The Deep Under-voltage Early Warning interrupt flag (DUVIF) will be set 250 ms before the chip enters Power-off. This will give the CPU a chance to take necessary actions before the power is switched off. The device will remain in the Power-off mode until a charger is connected. When a charger is detected, a normal power-up sequence is started and the chip initializes to default state. The Deep Under-voltage delay time and Deep Under-voltage detection level are set in the Battery Protection Deep Under-voltage Register (BPDUV). The Parameter Registers can be locked after the initial configuration, prohibiting any further updates until the next Hardware Reset. Refer to "Register Description for Battery Protection" on page 128 for register descriptions.
22.3
Discharge Over-current Protection
The Current Battery Protection (CBP) monitors the cell current by sampling the shunt resistor voltage at the PPI/NNI input pins. A differential operational amplifier amplifies the voltage with a suitable gain. The output from the operational amplifier is compared to an accurate, programmable On-chip voltage reference by an Analog Comparator. If the shunt resistor voltage is above the Discharge Over-current Detection level for a time longer than Over-current Protection Reaction Time, the chip activates Discharge Over-current Protection. A sampled system clocked by the internal ULP Oscillator is used for Over-current and Short-circuit Protection. This ensures a reliable clock source, off-set cancellation and low power consumption. When the Discharge Over-current Protection is activated, the external D-FET, PC-FET, and CFET are disabled and a Current Protection Timer is started. This timer ensures that the FETs are disabled for at least one second. The application software must then set the DFE and CFE bits in the FET Control and Status Register to re-enable normal operation. If the D-FET is re-enabled while the loading of the battery still is too large, the Discharge Over-current Protection will be activated again.
22.4
Charge Over-current Protection
If the voltage at the PPI/NNI pins is above the Charge Over-current Detection level for a time longer than Over-current Protection Reaction Time, the chip activates Charge Over-current Protection. When the Charge Over-current Protection is activated, the external D-FET, PC-FET, and C-FET are disabled and a Current Protection Timer is started. This timer ensures that the FETs are disabled for at least one second. The application software must then set the DFE and CFE bits in the FET Control and Status Register to re-enable normal operation. If the C-FET is re-enabled and the charger continues to supply too high currents, the Charge Over-current Protection will be activated again.
126
ATmega406
2548E-AVR-07/06
ATmega406
22.5 Short-circuit Protection
A second level of high current detection is provided to enable a faster response time to very large discharge currents. If a discharge current larger than the Short-circuit Detection Level is present for a period longer than Short-circuit Reaction Time, the Short-circuit Protection is activated. When the Short-circuit Protection is activated, the external D-FET, PC-FET, and C-FET are disabled and a Current Protection Timer is started. This timer ensures that the D-FET, PC-FET, and C-FET are disabled for at least one second. The application software must then set the DFE and CFE bits in the FET Control and Status Register to re-enable normal operation. If the D-FET is re-enabled before the cause of the short-circuit condition is removed, the Short-circuit Protection will be activated again. The Over-current and Short-circuit Protection parameters are programmable to adapt to different types of batteries. The parameters are set by writing to I/O Registers. The Parameter Registers can be locked after the initial configuration, prohibiting any further updates until the next Hardware Reset. Refer to "Register Description for Battery Protection" on page 128 for register descriptions.
22.6
Battery Protection CPU Interface
The Battery Protection CPU Interface is illustrated in Figure 22-1. Figure 22-1. Battery Protection CPU Interface
8-BIT DATA BUS
Battery Protection Parameter Lock Register
LOCK?
LOCK?
LOCK? Interrupt Request 8 / Interrupt Acknowledge
Battery Protection Level Register
Battery Protection Timing Register
Battery Protection Control Register
4 / PPI NNI Current Battery Protection Battery Protection Interrupt Register
4 /
VFET
Voltage Battery Protection Deep Under-voltage Power-off
Current Protection FET Control
Each protection has an Interrupt Flag. Each Flag can be read and cleared by the CPU, and each flag has an individual interrupt enable. All enabled flags are combined into a single battery protection interrupt request to the CPU. This interrupt can wake up the CPU from any operation mode, except Power-off. The interrupt flags are cleared by writing a logic `1' to their bit locations from the CPU. Note that there are neither flags nor status bits indicating that the chip has entered the Power Off mode. This is because the CPU is powered down in this mode. The CPU will, however be able
127
2548E-AVR-07/06
to detect that it came from a Power-off situation by monitoring CPU reset flags when it resumes operation.
22.7
Register Description for Battery Protection
The Battery Protection module operates in a different clock domain than the CPU. Whenever a new value is written to BPCR, BPDUV, BPOCD, BPSCD, or CPBTR, the value must be synchronized to the Battery Protection clock domain. Subsequent writes to this register should not be made during this synchronization. Therefore, after writing to one of these registers, the same register should not be re-written within the next 8 CPU clock periods. Note that each register is synchronized independently of the others.
22.7.1
BPPLR - Battery Protection Parameter Lock Register
Bit (0xF8) Read/Write Initial Value 7 - R 0 6 - R 0 5 - R 0 4 - R 0 3 - R 0 2 - R 0 1 BPPLE R/W 0 0 BPPL R/W 0 BPPLR
* Bit 7:2 - Res: Reserved Bits These bits are reserved bits in the ATmega406 and will always read as zero. * Bit 1 - BPPLE: Battery Protection Parameter Lock Enable * Bit 0 - BPPL: Battery Protection Parameter Lock The Battery Protection parameters set in the Battery Protection Parameter Registers and the disable function set in the Battery Protection Disable Register can be locked from any further software updates. Once locked, these registers cannot be accessed until the next hardware reset. This provides a safe method for protecting these registers from unintentional modification by software runaway. It is recommended that software sets these registers shortly after reset, and then protects these registers from any further updates. To lock these registers, the following algorithm must be followed: 1. In the same operation, write a logic one to BPPLE and BPPL. 2. Within the next four clock cycles, in the same operation. write a logic zero to BPPLE and a logic one to BPPL. The Battery Protection Parameter Registers are BPCR, CBPTR, BPOCP, BPSCD and BPDUV. 22.7.2 BPCR - Battery Protection Control Register
Bit (0xF7) Read/Write Initial Value 7 - R 0 6 - R 0 5 - R 0 4 - R 0 3 DUVD R/W 0 2 SCD R/W 0 1 DCD R/W 0 0 CCD R/W 0 BPCR
* Bit 7:4 - Res: Reserved Bits These bits are reserved bits in the ATmega406 and will always read as zero. * Bit 3 - DUVD: Deep Under-voltage Protection Disable
128
ATmega406
2548E-AVR-07/06
ATmega406
When the DUVD bit is set, the Deep Under-voltage Protection is disabled. The Deep Under-voltage Detection will be disabled, and any Deep Under-voltage condition will be ignored * Bit 2 - SCD: Short Circuit Protection Disabled When the SCD bit is set, the Short-circuit Protection is disabled. The Short-circuit Detection will be disabled, and any Short-circuit condition will be ignored. * Bit 1 - DCD: Discharge Over-current Protection Disable When the DCD bit is set, the Discharge Over-current Protection is disabled. The Discharge Over-current Detection will be disabled, and any Discharge Over-current condition will be ignored.
* Bit 0 - CCD: Charge Over-current Protection Disable When the CCD bit is set, the Charge Over-current Protection is disabled. The Charge Over-current Detection will be disabled, and any Charge Over-current condition will be ignored. 22.7.3 CBPTR - Current Battery Protection Timing Register
Bit (0xF6) Read/Write Initial Value R/W 0 7 6 SCPT[3:0] R/W 0 R/W 0 R/W 0 R/W 0 5 4 3 2 OCPT[3:0] R/W 0 R/W 0 R/W 0 1 0 CBPTR
* Bit 7:4 - SCPT3:0: Short-circuit Protection Timing These bits control the delay of the Short-circuit Protection. See Table 22-2. Table 22-2. SCPT[3:0] with Corresponding Short-circuit Delay Time
Short-circuit Protection Reaction Time SCPT[3:0] 0000 0001 0010 0011 Typ 61 s 122 s 183 s 244 s SCPT[3:0] 0100 0101 0110 0111 Typ 305 s 366 s 427 s 488 s SCPT[3:0] 1000 1001 1010 1011 Typ 610 s 732 s 854 s 976 s SCPT[3:0] 1100 1101 1110 1111 Typ 1098 s 1220 s 1342 s 1464 s
* Bit 3:0 - OCPT3:0: Over-current Protection Timing These bits control the delay of the Charge and Discharge Current Protection. See Table 22-3. Note that the same setting applies to both types of over-current protection. Table 22-3. OCPT[3:0] with Corresponding Over-current Delay Time
Over-current Protection Reaction Time OCPT[3:0] 0000 0001 0010 0011 Typ 1 ms 2 ms 4 ms 6 ms OCPT[3:0] 0100 0101 0110 0111 Typ 8 ms 10 ms 12 ms 14 ms OCPT[3:0] 1000 1001 1010 1011 Typ 16 ms 18 ms 20 ms 22 ms OCPT[3:0] 1100 1101 1110 1111 Typ 24 ms 26 ms 28 ms 30 ms
129
2548E-AVR-07/06
22.7.4
BPOCD - Battery Protection Over-current Detection Level Register
Bit (0xF5) Read/Write Initial Value R/W 0 7 6 DCDL[3:0] R/W 0 R/W 0 R/W 0 R/W 0 5 4 3 2 CCDL[3:0] R/W 0 R/W 0 R/W 0 1 0 BPOCD
* Bits 7:4 - DCDL3:0: Discharge Over-current Detection Level These bits set the RSENSE voltage level for detection of Discharge Over-current, as defined in Table 22-4.
Table 22-4.
DCDL[3:0] with Corresponding RSENSE Voltage for Discharge Over-current Detection Level
Discharge Over-current Protection Detection Level
DCDL[3:0] 0000 0001 0010 0011
Typ 0.050V 0.055V 0.060V 0.065V
DCDL[3:0] 0100 0101 0110 0111
Typ 0.070V 0.080V 0.090V 0.100V
DCDL[3:0] 1000 1001 1010 1011
Typ 0.110V 0.120V 0.130V 0.140V
DCDL[3:0] 1100 1101 1110 1111
Typ 0.160V 0.180V 0.200V 0.220V
* Bits 3:0 - CCDL3:0: Charge Over-current Detection Level These bits set the RSENSE voltage level for detection of Charge Over-current, as defined in Table 22-5. Table 22-5. CCDL[3:0] with Corresponding RSENSE Voltage for Charge Over-current Detection Level
Charge Over-current Protection Detection Level CCDL[3:0] 0000 0001 0010 0011 Typ 0.050V 0.055V 0.060V 0.065V CCDL[3:0] 0100 0101 0110 0111 Typ 0.070V 0.080V 0.090V 0.100V CCDL[3:0] 1000 1001 1010 1011 Typ 0.110V 0.120V 0.130V 0.140V CCDL[3:0] 1100 1101 1110 1111 Typ 0.160V 0.180V 0.200V 0.220V
22.7.5
BPSCD - Battery Protection Short-circuit Detection Level Register
Bit (0xF4) Read/Write Initial Value 7 - R 0 6 - R 0 5 - R 0 4 - R 0 R/W 0 3 2 SCDL[3:0] R/W 0 R/W 0 R/W 0 1 0 BPSCD
* Bit 7:4 - Res: Reserved Bits These bits are reserved bits in the ATmega406 and will always read as zero. * Bits 3:0 - SCDL3:0: Short-circuit Detection Level These bits set the RSENSE voltage level for detection of Short-circuit in the discharge direction, as defined in Table 22-6 on page 131.
130
ATmega406
2548E-AVR-07/06
ATmega406
Table 22-6. SCDL[3:0] with Corresponding RSENSE Voltage for Short-circuit Detection Level
Short-circuit Protection Detection Level SCDL[3:0] 0000 0001 0010 0011 Typ 0.100V 0.110V 0.120V 0.130V SCDL[3:0] 0100 0101 0110 0111 Typ 0.140V 0.160V 0.180V 0.200V SCDL[3:0] 1000 1001 1010 1011 Typ 0.220V 0.240V 0.260V 0.280V SCDL[3:0] 1100 1101 1110 1111 Typ 0.320V 0.360V 0.400V 0.440V
22.7.6
BPDUV - Battery Protection Deep Under Voltage Register
Bit (0xF3) Read/Write Initial Value 7 - R 0 6 - R 0 5 DUVT[1:0] R/W 0 R/W 0 R/W 0 4 3 2 DUDL[3:0] R/W 0 R/W 0 R/W 0 1 0 BPDUV
* Bit 7:6 - Res: Reserved Bits These bits are reserved bits in the ATmega406 and will always read as zero. * Bits 5:4 - DUVT1:0: Deep Under-voltage Timing These bits set the Deep Under-voltage Protection delay. Table 22-7.
DUVT1:0 00 01 10 11
DUVT[1:0] with Corresponding Deep Under-voltage Delay
Deep Under-voltage Delay 750 ms 1000 ms 1250 ms 1500 ms
* Bits 3:0 - DUDL3:0: Deep Under-voltage Detection Level These bits set the Deep Under-voltage detection level. Table 22-8.
DUDL[3:0] 0000 0001 0010 0011 0100 0101 0110 0111
DUDL[3:0] with Corresponding Deep Under-voltage Detection Level
Typ 4.71V 5.03V 5.34V 5.66V 5.97V 6.29V 6.60V 6.91V DUDL[3:0] 1000 1001 1010 1011 1100 1101 1110 1111 Typ 7.23V 7.54V 7.86V 8.17V 8.49V 8.80V 9.11V 9.43V
131
2548E-AVR-07/06
22.7.7
BPIR - Battery Protection Interrupt Register
Bit (0xF2) Read/Write Initial Value 7 DUVIF R/W 0 6 COCIF R/W 0 5 DOCIF R/W 0 4 SCIF R/W 0 3 DUVIE R/W 0 2 COCIE R/W 0 1 DOCIE R/W 0 0 SCIE R/W 0 BPIR
* Bit 7 - DUVIF: Deep Under-voltage Early Warning Interrupt Flag If the voltage at VFET pin is below the Deep Under-voltage detection level and only 250 ms is left of the Deep Under-voltage delay, DUVIF becomes set. The flag must be cleared by writing a logical one to it. * Bit 6 - COCIF: Charge Over-current Protection Activated Interrupt Flag When the Charge Over-current Protection is activated, COCIF becomes set. The flag must be cleared by writing a logical one to it. * Bit 5 - DOCIF: Discharge Over-current Protection Activated Interrupt Flag When the Discharge Over-current Protection is activated, DOCIF becomes set. The flag must be cleared by writing a logical one to it. * Bit 4 - SCIF: Short-circuit Protection Activated Interrupt Flag When the Short-circuit Protection is activated, SCIF becomes set. The flag must be cleared by writing a logical one to it. * Bit 3 - DUVIE: Deep Under-voltage Early Warning Interrupt Enable The DUVIE bit enables interrupt caused by the Deep Under-voltage Early Warning Interrupt Flag * Bit 2 - COCIE: Charge Over-current Protection Activated Interrupt Enable The COCIE bit enables interrupt caused by the Charge Over-current Protection Activated Interrupt Flag. * Bit 1 - DOCIE: Discharge Over-current Protection Activated Interrupt Enable The DOCIE bit enables interrupt caused by the Discharge Over-current Protection Activated Interrupt Flag. * Bit 0 - SCIE: Short-circuit Protection Activated Interrupt Enable The SCIE bit enables interrupt caused by the Short-circuit Protection Activated Interrupt Flag. If one of the Battery Protection Interrupt Flags is set, and the corresponding Interrupt Enable bit and the I-bit in the Status Register (SREG) are set, the MCU will jump to the Battery Protection interrupt vector. The application software must read the Battery Protection Interrupt Register to determine the cause of the interrupt. The interrupt flags will not be cleared when the interrupt routine is executed, they must be cleared by writing a logical one to them.
132
ATmega406
2548E-AVR-07/06
ATmega406
23. FET Control
In addition to the FET disable control signals from the battery protection circuitry, the CPU may disable the Charge FET (C-FET), the Discharge FET (D-FET), or both, by writing to the FET Control Register. Note that the CPU is never allowed to enable a FET that is disabled by the battery protection circuitry. The FET control is shown in Figure 23-1 on page 133. The PWM output from the 8-bit Timer/Counter0, OC0B, can be configured to drive the C-FET, Precharge FET (PC-FET) or both directly. This can be useful for controlling the charging of the battery cells. The PWM is configured by the COM0B1:0 and WGM02:0 bits in the TCCR0A/TCCR0B registers. Note that the OC0B pins does not need to be configured as an output. This means that the PWM output can be used to drive the C-FET and/or the PC-FET without occupying the OC0B-pin. If C-FET is disabled and D-FET enabled, discharge current will run through the body-drain diode of the C-FET and vice versa. To avoid the potential heat problem from this situation, software must ensure that D-FET is not disabled when a charge current is flowing, and that C-FET is not disabled when a discharge current is flowing. If the battery has been deeply discharged, large surge currents may result when a charger is connected. In this case, it is recommended to first pre charge the battery through a current limiting resistor. For this purpose, ATmega406 provides a Precharge FET (PC-FET) control output. This output is default enabled. If ATmega406 has entered the Power-off mode, all FET control outputs will be disabled. When a charger is connected, the CPU will wake up. When waking up from Power-off mode, the C-FET and D-FET control outputs will remain disabled while PC-FET is default enabled. When the CPU detects that the cell voltages have risen enough to allow normal charging, it should enable the C-FET and D-FET control outputs and disable the PC-FET control output. If the Current Battery Protection has been activated, the Current Protection Timer will ensure a hold-off time of 1 second before software can re-enable the external FETs. Figure 23-1. FET Control Block Diagram
Power-off Mode CURRENT_PROTECTION Current Protection Timer
OC0B
PWMOC
1
CFE
8-BIT D ATA BU S
0
FET Control and Status Register
FET Driver PWMOPC
1
OC
FET Driver
OPC
PFD
0
DFE
FET Driver
OD
133
2548E-AVR-07/06
23.1
FET Driver
Figure 23-2. Connection of external FETs
Rpc
Rpf
+
Rdf RN Rcf
PVT
OD
OC
OPC
BATT
The connection of external FETs to OD, OC, and OPC is shown in Figure 23-2. When switching on an FET, the output pulls the gate quickly low to avoid heating of the FET. When the FET is switched completely on, the output changes operation mode in order to reduce current consumption. The gate-source voltage for the FET when switched on, |VGS_ON|, is limited to 13V 15%. When disabling an external FET, the FET Driver output quickly pushes the gate voltage to the source pin potential, making the gate-source voltage of the FET close to zero. This disables the FET, and the FET Driver output switches operation mode to high impedance in order to reduce current consumption. The external resistor will keep the gate-source voltage at zero until the FET is enabled again and its gate is pulled low as explained above.
23.2
Register Description for FET Control
The FET Controller operates in a different clock domain than the CPU. Whenever a new value is written to the FCSR, the value must be synchronized to the FET Controller clock domain. Subsequent writes to this register should not be made during this synchronization. Therefore, after writing to this register, a guard time of 3 ULP Oscillator cycles + 3 CPU clock cycles is required. It is recommended that software only reads the FCSR when handling a Battery Protection Interrupt (BPINT).
23.2.1
FCSR - FET Control and Status Register
Bit (0xF0) Read/Write Initial Value 7 - R 0 6 - R 0 5 PWMOC R/W 0 4 PWMOPC R/W 0 3 CPS R 0 2 DFE R/W 0 1 CFE R/W 0 0 PFD R/W 0 FCSR
* Bits 7:6 - Res: Reserved Bits These bits are reserved bits in the ATmega406, and will always read as zero. * Bit 5 - PWMOC: Pulse Width Modulation of OC output
134
ATmega406
2548E-AVR-07/06
ATmega406
When the PWMOC is cleared (zero), the CFE bit and the battery protection circuitry controls the OC output. When this bit is set (one), the OC output will be the logical AND of the PWM output from the 8-bit Timer/Counter0 and the inverse of CURRENT_PROTECTION from the Battery Protection circuitry. * Bit 4 - PWMOPC: Pulse Width Modulation of OPC output When the PWMOPC is cleared (zero), the PFD bit and the battery protection circuitry controls the OPC output. When this bit is set (one), the OPC output will be the logical AND of the PWM output from the 8-bit Timer/Counter0 and the inverse of CURRENT_PROTECTION from the Battery Protection circuitry. * Bit 3 - CPS: Current Protection Status The CPS bit shows the status of the Current Protection. This bit is set (one) when the Current Protection Timer is activated, and is cleared (zero) when the hold-off time has elapsed. * Bit 2 - DFE: Discharge FET Enable When the DFE bit is cleared (zero), the Discharge FET will be disabled regardless of the state of the Battery Protection circuitry. When this bit is set (one), the Discharge FET state is determined by the Battery Protection circuitry. This bit will be cleared when CURRENT_PROTECTION is set (one). * Bit 1 - CFE: Charge FET Enable When the CFE bit is cleared (zero), the Charge FET will be disabled regardless of the state of the Battery Protection circuitry. When this bit is set (one), the Charge FET state is determined by the Battery Protection circuitry. This bit will be cleared when CURRENT_PROTECTION is set (one). * Bit 0 - PFD: Precharge FET Disable The PFD bit provides complete control of the Precharge FET. When the PFD bit is cleared (zero), the Precharge FET will be enabled. When the PFD bit is cleared, the Precharge FET will be enabled. When the PFD bit is set (one), the Precharge FET will be disabled. This bit will be cleared when the CURRENT_PROTECTION is set (one)
135
2548E-AVR-07/06
24. Cell Balancing
ATmega406 incorporates cell balancing FETs. The chip provides one cell balancing FET for each battery cell in series. The FETs are directly controlled by the application software, allowing the cell balancing algorithms to be implemented in software. The FETs are connected in parallel with the individual battery cells. The cell balancing is illustrated in Figure 24-1. The figure shows a four-cell configuration. The cell balancing FETs are disabled in the Power-off mode. Typical current through the Cell Balancing FETs (TCB) is 2 mA. The Cell Balancing FETs are controlled by the CBCR. Neighbouring FETs cannot be simultaneously enabled. If trying to enable two neighbouring FETs, both will be disabled. Figure 24-1. Cell Balancing
PV4
RP
PV3
RP TCB Level Shift Cell Balancing Control Register
PV2
RP TCB Level Shift
PV1
RP TCB RP
NV
Level Shift
136
ATmega406
2548E-AVR-07/06
8-BIT DATA BUS
TCB
Level Shift
ATmega406
24.1
24.1.1
Register Description
CBCR - Cell Balancing Control Register
Bit (0xF1) Read/Write Initial Value 7 - R 0 6 - R 0 5 - R 0 4 - R 0 3 CBE4 R/W 0 2 CBE3 R/W 0 1 CBE2 R/W 0 0 CBE1 R/W 0 CBCR
* Bit 7:4 - Res: Reserved Bits These bits are reserved bits in the ATmega406 and will always read as zero. * Bit 3 - CBE4: Cell Balancing Enable 4 When this bit is set, the integrated Cell Balancing FET between terminals PV4 and PV3 will be enabled. When the bit is cleared, the Cell Balancing FET will be disabled. The Cell Balancing FETs are always disabled in Power-off mode. CBE4 cannot be set if CBE3 is set. * Bit 2 - CBE3: Cell Balancing Enable 3 When this bit is set, the integrated Cell Balancing FET between terminals PV3 and PV2 will be enabled. When the bit is cleared, the Cell Balancing FET will be disabled. The Cell Balancing FETs are always disabled in Power-off mode. CBE3 cannot be set if CBE2 or CBE4 is set. * Bit 1 - CBE2: Cell Balancing Enable 2 When this bit is set, the integrated Cell Balancing FET between terminals PV2 and PV1 will be enabled. When the bit is cleared, the Cell Balancing FET will be disabled. The Cell Balancing FETs are always disabled in Power-off mode. CBE2 cannot be set if CBE1 or CBE3 is set. * Bit 0 - CBE1: Cell Balancing Enable 1 When this bit is set (one), the integrated Cell Balancing FET between terminals PV1 and NV will be enabled. When the bit is cleared (zero), the Cell Balancing FET will be disabled. The Cell Balancing FETs are always disabled in Power-off mode. CBE1 cannot be set if CBE2 is set.
137
2548E-AVR-07/06
25. 2-wire Serial Interface
25.1 Features
* * * * * * * * * *
Simple yet Powerful and Flexible Communication Interface, Only Two Bus Lines Needed Both Master and Slave Operation Supported Device can Operate as Transmitter or Receiver 7-bit Address Space allows up to 128 Different Slave Addresses Multi-master Arbitration Support Operates on 4 MHz Clock, achieving up to 100 kHz Data Transfer Speed Slew-rate Limited Output Drivers Noise Suppression Circuitry Rejects Spikes on Bus Lines Fully Programmable Slave Address with General Call Support Address Recognition Causes Wake-up when AVR is in Sleep Mode
25.2
Two-wire Serial Interface Bus Definition
The Two-wire Serial Interface (TWI) is ideally suited for typical microcontroller applications. The TWI protocol allows the systems designer to interconnect up to 128 different devices using only two bi-directional bus lines, one for clock (SCL) and one for data (SDA). The only external hardware needed to implement the bus is a single pull-up resistor for each of the TWI bus lines. All devices connected to the bus have individual addresses, and mechanisms for resolving bus contention are inherent in the TWI protocol. The PRTWI bit in "PRR0 - Power Reduction Register 0" on page 36 must be written to zero to enable TWI module. Figure 25-1. TWI Bus Interconnection
VBUS
Device 1
Device 2
Device 3
........
Device n
R1
R2
SDA
SCL
138
ATmega406
2548E-AVR-07/06
ATmega406
25.2.1 TWI Terminology The following definitions are frequently encountered in this section. Table 25-1.
Term Master Slave Transmitter Receiver
TWI Terminology
Description The device that initiates and terminates a transmission. The Master also generates the SCL clock. The device addressed by a Master. The device placing data on the bus. The device reading data from the bus.
25.2.2
Electrical Interconnection As depicted in Figure 25-1, both bus lines are connected to the positive supply voltage through pull-up resistors. The bus drivers of all TWI-compliant devices are open-drain or open-collector. This implements a wired-AND function which is essential to the operation of the interface. A low level on a TWI bus line is generated when one or more TWI devices output a zero. A high level is output when all TWI devices tri-state their outputs, allowing the pull-up resistors to pull the line high. Note that all AVR devices connected to the TWI bus must be powered in order to allow any bus operation. The number of devices that can be connected to the bus is only limited by the bus capacitance limit of 400 pF and the 7-bit slave address space. A detailed specification of the electrical characteristics of the TWI is given in "2-wire Serial Interface Characteristics" on page 229.
25.3
25.3.1
Data Transfer and Frame Format
Transferring Bits Each data bit transferred on the TWI bus is accompanied by a pulse on the clock line. The level of the data line must be stable when the clock line is high. The only exception to this rule is for generating start and stop conditions. Figure 25-2. Data Validity
SDA
SCL Data Stable Data Stable Data Change
139
2548E-AVR-07/06
25.3.2
START and STOP Conditions The Master initiates and terminates a data transmission. The transmission is initiated when the Master issues a START condition on the bus, and it is terminated when the Master issues a STOP condition. Between a START and a STOP condition, the bus is considered busy, and no other Master should try to seize control of the bus. A special case occurs when a new START condition is issued between a START and STOP condition. This is referred to as a REPEATED START condition, and is used when the Master wishes to initiate a new transfer without relinquishing control of the bus. After a REPEATED START, the bus is considered busy until the next STOP. This is identical to the START behavior, and therefore START is used to describe both START and REPEATED START for the remainder of this datasheet, unless otherwise noted. As depicted below, START and STOP conditions are signalled by changing the level of the SDA line when the SCL line is high. Figure 25-3. START, REPEATED START, and STOP Conditions
SDA
SCL
START
STOP START
REPEATED START
STOP
25.3.3
Address Packet Format All address packets transmitted on the TWI bus are nine bits long, consisting of seven address bits, one READ/WRITE control bit and an acknowledge bit. If the READ/WRITE bit is set, a read operation is to be performed, otherwise a write operation should be performed. When a slave recognizes that it is being addressed, it should acknowledge by pulling SDA low in the ninth SCL (ACK) cycle. If the addressed Slave is busy, or for some other reason can not service the Master's request, the SDA line should be left high in the ACK clock cycle. The Master can then transmit a STOP condition, or a REPEATED START condition to initiate a new transmission. An address packet consisting of a slave address and a READ or a WRITE bit is called SLA+R or SLA+W, respectively. The MSB of the address byte is transmitted first. Slave addresses can freely be allocated by the designer, but the address 0000 000 is reserved for a general call. When a general call is issued, all slaves should respond by pulling the SDA line low in the ACK cycle. A general call is used when a Master wishes to transmit the same message to several slaves in the system. When the general call address followed by a write bit is transmitted on the bus, all slaves set up to acknowledge the general call will pull the SDA line low in the ack cycle. The following data packets will then be received by all the slaves that acknowledged the general call. Note that transmitting the general call address followed by a Read bit is meaningless, as this would cause contention if several slaves started transmitting different data. All addresses of the format 1111 xxx should be reserved for future purposes.
140
ATmega406
2548E-AVR-07/06
ATmega406
Figure 25-4. Address Packet Format
Addr MSB SDA Addr LSB R/W ACK
SCL 1 START 2 7 8 9
25.3.4
Data Packet Format All data packets transmitted on the TWI bus are nine bits long, consisting of one data byte and an acknowledge bit. During a data transfer, the Master generates the clock and the START and STOP conditions, while the Receiver is responsible for acknowledging the reception. An Acknowledge (ACK) is signalled by the Receiver pulling the SDA line low during the ninth SCL cycle. If the Receiver leaves the SDA line high, a NACK is signalled. When the Receiver has received the last byte, or for some reason cannot receive any more bytes, it should inform the Transmitter by sending a NACK after the final byte. The MSB of the data byte is transmitted first. Figure 25-5. Data Packet Format
Data MSB Aggregate SDA SDA from Transmitter SDA from Receiver SCL from Master 1 SLA+R/W 2 7 Data Byte 8 9 STOP, REPEATED START, or Next Data Byte Data LSB ACK
25.3.5
Combining Address and Data Packets Into a Transmission A transmission basically consists of a START condition, a SLA+R/W, one or more data packets and a STOP condition. An empty message, consisting of a START followed by a STOP condition, is illegal. Note that the wired-ANDing of the SCL line can be used to implement handshaking between the Master and the Slave. The Slave can extend the SCL low period by pulling the SCL line low. This is useful if the clock speed set up by the Master is too fast for the Slave, or the Slave needs extra time for processing between the data transmissions. The Slave extending the SCL low period will not affect the SCL high period, which is determined by the Master. As a consequence, the Slave can reduce the TWI data transfer speed by prolonging the SCL duty cycle. Figure 25-6 shows a typical data transmission. Note that several data bytes can be transmitted between the SLA+R/W and the STOP condition, depending on the software protocol implemented by the application software.
141
2548E-AVR-07/06
Figure 25-6. Typical Data Transmission
Addr MSB SDA Addr LSB R/W ACK Data MSB Data LSB ACK
SCL 1 START 2 7 SLA+R/W 8 9 1 2 Data Byte 7 8 9 STOP
25.4
Multi-master Bus Systems, Arbitration and Synchronization
The TWI protocol allows bus systems with several masters. Special concerns have been taken in order to ensure that transmissions will proceed as normal, even if two or more masters initiate a transmission at the same time. Two problems arise in multi-master systems: * An algorithm must be implemented allowing only one of the masters to complete the transmission. All other masters should cease transmission when they discover that they have lost the selection process. This selection process is called arbitration. When a contending master discovers that it has lost the arbitration process, it should immediately switch to Slave mode to check whether it is being addressed by the winning master. The fact that multiple masters have started transmission at the same time should not be detectable to the slaves (i.e., the data being transferred on the bus must not be corrupted). * Different masters may use different SCL frequencies. A scheme must be devised to synchronize the serial clocks from all masters, in order to let the transmission proceed in a lockstep fashion. This will facilitate the arbitration process. The wired-ANDing of the bus lines is used to solve both these problems. The serial clocks from all masters will be wired-ANDed, yielding a combined clock with a high period equal to the one from the master with the shortest high period. The low period of the combined clock is equal to the low period of the master with the longest low period. Note that all masters listen to the SCL line, effectively starting to count their SCL high and low Time-out periods when the combined SCL line goes high or low, respectively.
142
ATmega406
2548E-AVR-07/06
ATmega406
Figure 25-7. SCL Synchronization between Multiple Masters
TA low TA high
SCL from Master A
SCL from Master B
SCL bus Line TB low Masters Start Counting Low Period TB high Masters Start Counting High Period
Arbitration is carried out by all masters continuously monitoring the SDA line after outputting data. If the value read from the SDA line does not match the value the master had output, it has lost the arbitration. Note that a master can only lose arbitration when it outputs a high SDA value while another master outputs a low value. The losing master should immediately go to Slave mode, checking if it is being addressed by the winning master. The SDA line should be left high, but losing masters are allowed to generate a clock signal until the end of the current data or address packet. Arbitration will continue until only one master remains, and this may take many bits. If several masters are trying to address the same slave, arbitration will continue into the data packet. Figure 25-8. Arbitration between Two Masters
START SDA from Master A Master A Loses Arbitration, SDA A SDA
SDA from Master B
SDA Line
Synchronized SCL Line
Note that arbitration is not allowed between: * A REPEATED START condition and a data bit. * A STOP condition and a data bit. * A REPEATED START and a STOP condition.
143
2548E-AVR-07/06
It is the user software's responsibility to ensure that these illegal arbitration conditions never occur. This implies that in multi-master systems, all data transfers must use the same composition of SLA+R/W and data packets. In other words: All transmissions must contain the same number of data packets, otherwise the result of the arbitration is undefined.
25.5
Overview of the TWI Module
The TWI module is comprised of several submodules, as shown in Figure 25-9. The shaded registers are accessible through the AVR data bus. Figure 25-9. Overview of the TWI Module
SCL
Slew-rate Control Spike Filter
SDA
Slew-rate Control Spike Filter
Bus Interface Unit
START / STOP Control Spike Suppression
Bit Rate Generator
Prescaler
Arbitration Detection
Address/Data Shift Register (TWDR)
Ack
Bit Rate Register (TWBR)
Address Match Unit
Address Register (TWAR)
Control Unit
Status Register (TWSR) Control Register (TWCR)
Address Comparator
State Machine and Status Control
25.5.1
SCL and SDA Pins These pins interface the AVR TWI with the rest of the MCU system. The output drivers contain a slew-rate limiter in order to conform to the TWI specification. The input stages contain a spike suppression unit removing spikes shorter than 50 ns.
144
ATmega406
2548E-AVR-07/06
TWI Unit
ATmega406
25.5.2 Bit Rate Generator Unit This unit controls the period of SCL when operating in a Master mode. The SCL period is controlled by settings in the TWI Bit Rate Register (TWBR) and the Prescaler bits in the TWI Status Register (TWSR). Slave operation does not depend on Bit Rate or Prescaler settings, but the CPU clock frequency in the slave must be at least 16 times higher than the SCL frequency. Note that slaves may prolong the SCL low period, thereby reducing the average TWI bus clock period. The SCL frequency is generated according to the following equation: TWI Clock frequency SCL frequency = ---------------------------------------------------------TWPS 16 + 2(TWBR) 4 * TWBR = Value of the TWI Bit Rate Register. * TWPS = Value of the prescaler bits in the TWI Status Register.
Notes: 1. TWBR should be 10 or higher if the TWI operates in Master mode. If TWBR is lower than 10, the master may produce an incorrect output on SDA and SCL for the reminder of the byte. The problem occurs when operating the TWI in Master mode, sending Start + SLA + R/W to a slave (a slave does not need to be connected to the bus for the condition to happen). 2. The TWI clock is 4 MHz, see "Calibrated Fast RC Oscillator" on page 26.
25.5.3
Bus Interface Unit This unit contains the Data and Address Shift Register (TWDR), a START/STOP Controller and Arbitration detection hardware. The TWDR contains the address or data bytes to be transmitted, or the address or data bytes received. In addition to the 8-bit TWDR, the Bus Interface Unit also contains a register containing the (N)ACK bit to be transmitted or received. This (N)ACK Register is not directly accessible by the application software. However, when receiving, it can be set or cleared by manipulating the TWI Control Register (TWCR). When in Transmitter mode, the value of the received (N)ACK bit can be determined by the value in the TWSR. The START/STOP Controller is responsible for generation and detection of START, REPEATED START, and STOP conditions. The START/STOP controller is able to detect START and STOP conditions even when the AVR MCU is in one of the sleep modes, enabling the MCU to wake up if addressed by a Master. If the TWI has initiated a transmission as Master, the Arbitration Detection hardware continuously monitors the transmission trying to determine if arbitration is in process. If the TWI has lost an arbitration, the Control Unit is informed. Correct action can then be taken and appropriate status codes generated.
25.5.4
Address Match Unit The Address Match unit checks if received address bytes match the 7-bit address in the TWI Address Register (TWAR). If the TWI General Call Recognition Enable (TWGCE) bit in the TWAR is written to one, all incoming address bits will also be compared against the General Call address. Upon an address match, the Control unit is informed, allowing correct action to be taken. The TWI may or may not acknowledge its address, depending on settings in the TWCR. The Address Match unit is able to compare addresses even when the AVR MCU is in sleep mode, enabling the MCU to wake-up if addressed by a Master.
145
2548E-AVR-07/06
25.5.5
Control Unit The Control unit monitors the TWI bus and generates responses corresponding to settings in the TWI Control Register (TWCR). When an event requiring the attention of the application occurs on the TWI bus, the TWI Interrupt Flag (TWINT) is asserted. In the next clock cycle, the TWI Status Register (TWSR) is updated with a status code identifying the event. The TWSR only contains relevant status information when the TWI interrupt flag is asserted. At all other times, the TWSR contains a special status code indicating that no relevant status information is available. As long as the TWINT flag is set, the SCL line is held low. This allows the application software to complete its tasks before allowing the TWI transmission to continue. The TWINT flag is set in the following situations: * After the TWI has transmitted a START/REPEATED START condition. * After the TWI has transmitted SLA+R/W. * After the TWI has transmitted an address byte. * After the TWI has lost arbitration. * After the TWI has been addressed by own slave address or general call. * After the TWI has received a data byte. * After a STOP or REPEATED START has been received while still addressed as a Slave. * When a bus error has occurred due to an illegal START or STOP condition.
146
ATmega406
2548E-AVR-07/06
ATmega406
25.6
25.6.1
TWI Register Description
TWBR - TWI Bit Rate Register
Bit (0xB8) Read/Write Initial Value 7 TWBR7 R/W 0 6 TWBR6 R/W 0 5 TWBR5 R/W 0 4 TWBR4 R/W 0 3 TWBR3 R/W 0 2 TWBR2 R/W 0 1 TWBR1 R/W 0 0 TWBR0 R/W 0 TWBR
* Bits 7:0 - TWI Bit Rate Register TWBR selects the division factor for the bit rate generator. The bit rate generator is a frequency divider which generates the SCL clock frequency in the Master modes. See "Bit Rate Generator Unit" on page 145 for calculating bit rates. 25.6.2 TWCR - TWI Control Register
Bit (0xBC) Read/Write Initial Value 7 TWINT R/W 0 6 TWEA R/W 0 5 TWSTA R/W 0 4 TWSTO R/W 0 3 TWWC R 0 2 TWEN R/W 0 1 - R 0 0 TWIE R/W 0 TWCR
The TWCR is used to control the operation of the TWI. It is used to enable the TWI, to initiate a Master access by applying a START condition to the bus, to generate a Receiver acknowledge, to generate a stop condition, and to control halting of the bus while the data to be written to the bus are written to the TWDR. It also indicates a write collision if data is attempted written to TWDR while the register is inaccessible. * Bit 7 - TWINT: TWI Interrupt Flag This bit is set by hardware when the TWI has finished its current job and expects application software response. If the I-bit in SREG and TWIE in TWCR are set, the MCU will jump to the TWI Interrupt Vector. While the TWINT flag is set, the SCL low period is stretched. The TWINT flag must be cleared by software by writing a logic one to it. Note that this flag is not automatically cleared by hardware when executing the interrupt routine. Also note that clearing this flag starts the operation of the TWI, so all accesses to the TWI Address Register (TWAR), TWI Status Register (TWSR), and TWI Data Register (TWDR) must be complete before clearing this flag. * Bit 6 - TWEA: TWI Enable Acknowledge Bit The TWEA bit controls the generation of the acknowledge pulse. If the TWEA bit is written to one, the ACK pulse is generated on the TWI bus if the following conditions are met: 1. The device's own slave address has been received. 2. A general call has been received, while the TWGCE bit in the TWAR is set. 3. A data byte has been received in Master Receiver or Slave Receiver mode. By writing the TWEA bit to zero, the device can be virtually disconnected from the Two-wire Serial Bus temporarily. Address recognition can then be resumed by writing the TWEA bit to one again. * Bit 5 - TWSTA: TWI START Condition Bit The application writes the TWSTA bit to one when it desires to become a Master on the Twowire Serial Bus. The TWI hardware checks if the bus is available, and generates a START con-
147
2548E-AVR-07/06
dition on the bus if it is free. However, if the bus is not free, the TWI waits until a STOP condition is detected, and then generates a new START condition to claim the Bus Master status. TWSTA is cleared by the TWI hardware when the START condition has been transmitted. * Bit 4 - TWSTO: TWI STOP Condition Bit Writing the TWSTO bit to one in Master mode will generate a STOP condition on the Two-wire Serial Bus. When the STOP condition is executed on the bus, the TWSTO bit is cleared automatically. In Slave mode, setting the TWSTO bit can be used to recover from an error condition. This will not generate a STOP condition, but the TWI returns to a well-defined unaddressed Slave mode and releases the SCL and SDA lines to a high impedance state. * Bit 3 - TWWC: TWI Write Collision Flag The TWWC bit is set when attempting to write to the TWI Data Register - TWDR when TWINT is low. This flag is cleared by writing the TWDR Register when TWINT is high. * Bit 2 - TWEN: TWI Enable Bit The TWEN bit enables TWI operation and activates the TWI interface. When TWEN is written to one, the TWI takes control over the I/O pins connected to the SCL and SDA pins, enabling the slew-rate limiters and spike filters. If this bit is written to zero, the TWI is switched off and all TWI transmissions are terminated, regardless of any ongoing operation. * Bit 1 - Res: Reserved Bit This bit is a reserved bit and will always read as zero. * Bit 0 - TWIE: TWI Interrupt Enable When this bit is written to one, and the I-bit in SREG is set, the TWI interrupt request will be activated for as long as the TWINT flag is high. 25.6.3 TWSR - TWI Status Register
Bit (0xB9) Read/Write Initial Value 7 TWS7 R 1 6 TWS6 R 1 5 TWS5 R 1 4 TWS4 R 1 3 TWS3 R 1 2 - R 0 1 TWPS1 R/W 0 0 TWPS0 R/W 0 TWSR
* Bits 7:3 - TWS: TWI Status These five bits reflect the status of the TWI logic and the Two-wire Serial Bus. The different status codes are described in Table 25-3 on page 156 through Table 25-6 on page 165. Note that the value read from TWSR contains both the 5-bit status value and the 2-bit prescaler value. The application designer should mask the prescaler bits to zero when checking the status bits. This makes status checking independent of prescaler setting. This approach is used in this datasheet, unless otherwise noted. * Bit 2 - Res: Reserved Bit This bit is reserved and will always read as zero. * Bits 1:0 - TWPS: TWI Prescaler Bits These bits can be read and written, and control the bit rate prescaler.
148
ATmega406
2548E-AVR-07/06
ATmega406
Table 25-2. TWI Bit Rate Prescaler
TWPS0 0 1 0 1 Prescaler Value 1 4 16 64
TWPS1 0 0 1 1
To calculate bit rates, see "Bit Rate Generator Unit" on page 145. The value of TWPS1:0 is used in the equation. 25.6.4 TWDR - TWI Data Register
Bit (0xBB) Read/Write Initial Value 7 TWD7 R/W 1 6 TWD6 R/W 1 5 TWD5 R/W 1 4 TWD4 R/W 1 3 TWD3 R/W 1 2 TWD2 R/W 1 1 TWD1 R/W 1 0 TWD0 R/W 1 TWDR
In Transmit mode, TWDR contains the next byte to be transmitted. In Receive mode, the TWDR contains the last byte received. It is writable while the TWI is not in the process of shifting a byte. This occurs when the TWI Interrupt Flag (TWINT) is set by hardware. Note that the data register cannot be initialized by the user before the first interrupt occurs. The data in TWDR remains stable as long as TWINT is set. While data is shifted out, data on the bus is simultaneously shifted in. TWDR always contains the last byte present on the bus, except after a wake-up from a sleep mode by the TWI interrupt. In this case, the contents of TWDR is undefined. In the case of a lost bus arbitration, no data is lost in the transition from Master to Slave. Handling of the ACK bit is controlled automatically by the TWI logic, the CPU cannot access the ACK bit directly. * Bits 7:0 - TWD: TWI Data Register These eight bits constitute the next data byte to be transmitted, or the latest data byte received on the Two-wire Serial Bus. 25.6.5 TWAR - TWI (Slave) Address Register
Bit (0xBA) Read/Write Initial Value 7 TWA6 R/W 1 6 TWA5 R/W 1 5 TWA4 R/W 1 4 TWA3 R/W 1 3 TWA2 R/W 1 2 TWA1 R/W 1 1 TWA0 R/W 1 0 TWGCE R/W 0 TWAR
The TWAR should be loaded with the 7-bit slave address (in the seven most significant bits of TWAR) to which the TWI will respond when programmed as a slave transmitter or Receiver, and not needed in the Master modes. In multi-master systems, TWAR must be set in masters which can be addressed as slaves by other masters. The LSB of TWAR is used to enable recognition of the general call address (0x00). There is an associated address comparator that looks for the slave address (or general call address if enabled) in the received serial address. If a match is found, an interrupt request is generated. * Bits 7:1 - TWA: TWI (Slave) Address Register These seven bits constitute the slave address of the TWI unit.
149
2548E-AVR-07/06
* Bit 0 - TWGCE: TWI General Call Recognition Enable Bit If set, this bit enables the recognition of a General Call given over the Two-wire Serial Bus. 25.6.6 TWAMR - TWI (Slave) Address Mask Register
Bit (0xBD) Read/Write Initial Value R/W 0 R/W 0 R/W 0 7 6 5 4 TWAM[6:0] R/W 0 R/W 0 R/W 0 R/W 0 3 2 1 0
- TWAMR
R 0
* Bits 7:1 - TWAM: TWI Address Mask The TWAMR can be loaded with a 7-bit Slave Address mask. Each of the bits in TWAMR can mask (disable) the corresponding address bits in the TWI Address Register (TWAR). If the mask bit is set to one then the address match logic ignores the compare between the incoming address bit and the corresponding bit in TWAR. Figure 25-10 shown the address match logic in detail. Figure 25-10. TWI Address Match Logic, Block Diagram
TWAR0 Address Bit 0 TWAMR0 Address Bit Comparator 0 Address Match
Address Bit Comparator 6..1
* Bit 0 - Res: Reserved Bit This bit is an unused bit in the ATmega406, and will always read as zero.
25.7
Using the TWI
The AVR TWI is byte-oriented and interrupt based. Interrupts are issued after all bus events, like reception of a byte or transmission of a START condition. Because the TWI is interrupt-based, the application software is free to carry on other operations during a TWI byte transfer. Note that the TWI Interrupt Enable (TWIE) bit in TWCR together with the Global Interrupt Enable bit in SREG allow the application to decide whether or not assertion of the TWINT flag should generate an interrupt request. If the TWIE bit is cleared, the application must poll the TWINT flag in order to detect actions on the TWI bus. When the TWINT flag is asserted, the TWI has finished an operation and awaits application response. In this case, the TWI Status Register (TWSR) contains a value indicating the current state of the TWI bus. The application software can then decide how the TWI should behave in the next TWI bus cycle by manipulating the TWCR and TWDR registers. Figure 25-11 is a simple example of how the application can interface to the TWI hardware. In this example, a Master wishes to transmit a single data byte to a Slave. This description is quite abstract, a more detailed explanation follows later in this section. A simple code example implementing the desired behavior is also presented.
150
ATmega406
2548E-AVR-07/06
ATmega406
Figure 25-11. Interfacing the Application to the TWI in a Typical Transmission
1. Application writes to TWCR to initiate transmission of START 3. Check TWSR to see if START was sent. Application loads SLA+W into TWDR, and loads appropriate control signals into TWCR, making sure that TWINT is written to one 5. Check TWSR to see if SLA+W was sent and ACK received. Application loads data into TWDR, and loads appropriate control signals into TWCR, making sure that TWINT is written to one 7. Check TWSR to see if data was sent and ACK received. Application loads appropriate control signals to send STOP into TWCR, making sure that TWINT is written to one Application Action
TWI bus
START
SLA+W
A
Data
A
STOP
TWI Hardware Action
2. TWINT set. Status code indicates START condition sent
4. TWINT set. Status code indicates SLA+W sent, ACK received
6. TWINT set. Status code indicates data sent, ACK received
Indicates TWINT set
1. The first step in a TWI transmission is to transmit a START condition. This is done by writing a specific value into TWCR, instructing the TWI hardware to transmit a START condition. Which value to write is described later on. However, it is important that the TWINT bit is set in the value written. Writing a one to TWINT clears the flag. The TWI will not start any operation as long as the TWINT bit in TWCR is set. Immediately after the application has cleared TWINT, the TWI will initiate transmission of the START condition. 2. When the START condition has been transmitted, the TWINT flag in TWCR is set, and TWSR is updated with a status code indicating that the START condition has successfully been sent. 3. The application software should now examine the value of TWSR, to make sure that the START condition was successfully transmitted. If TWSR indicates otherwise, the application software might take some special action, like calling an error routine. Assuming that the status code is as expected, the application must load SLA+W into TWDR. Remember that TWDR is used both for address and data. After TWDR has been loaded with the desired SLA+W, a specific value must be written to TWCR, instructing the TWI hardware to transmit the SLA+W present in TWDR. Which value to write is described later on. However, it is important that the TWINT bit is set in the value written. Writing a one to TWINT clears the flag. The TWI will not start any operation as long as the TWINT bit in TWCR is set. Immediately after the application has cleared TWINT, the TWI will initiate transmission of the address packet. 4. When the address packet has been transmitted, the TWINT flag in TWCR is set, and TWSR is updated with a status code indicating that the address packet has successfully been sent. The status code will also reflect whether a slave acknowledged the packet or not. 5. The application software should now examine the value of TWSR, to make sure that the address packet was successfully transmitted, and that the value of the ACK bit was as expected. If TWSR indicates otherwise, the application software might take some special action, like calling an error routine. Assuming that the status code is as expected, the application must load a data packet into TWDR. Subsequently, a specific value must be written to TWCR, instructing the TWI hardware to transmit the data packet present in TWDR. Which value to write is described later on. However, it is important that the TWINT bit is set in the value written. Writing a one to TWINT clears the flag. The TWI will
151
2548E-AVR-07/06
not start any operation as long as the TWINT bit in TWCR is set. Immediately after the application has cleared TWINT, the TWI will initiate transmission of the data packet. 6. When the data packet has been transmitted, the TWINT flag in TWCR is set, and TWSR is updated with a status code indicating that the data packet has successfully been sent. The status code will also reflect whether a slave acknowledged the packet or not. 7. The application software should now examine the value of TWSR, to make sure that the data packet was successfully transmitted, and that the value of the ACK bit was as expected. If TWSR indicates otherwise, the application software might take some special action, like calling an error routine. Assuming that the status code is as expected, the application must write a specific value to TWCR, instructing the TWI hardware to transmit a STOP condition. Which value to write is described later on. However, it is important that the TWINT bit is set in the value written. Writing a one to TWINT clears the flag. The TWI will not start any operation as long as the TWINT bit in TWCR is set. Immediately after the application has cleared TWINT, the TWI will initiate transmission of the STOP condition. Note that TWINT is NOT set after a STOP condition has been sent. Even though this example is simple, it shows the principles involved in all TWI transmissions. These can be summarized as follows: * When the TWI has finished an operation and expects application response, the TWINT flag is set. The SCL line is pulled low until TWINT is cleared. * When the TWINT flag is set, the user must update all TWI registers with the value relevant for the next TWI bus cycle. As an example, TWDR must be loaded with the value to be transmitted in the next bus cycle. * After all TWI Register updates and other pending application software tasks have been completed, TWCR is written. When writing TWCR, the TWINT bit should be set. Writing a one to TWINT clears the flag. The TWI will then commence executing whatever operation was specified by the TWCR setting. In the following an assembly and C implementation of the example is given. Note that the code below assumes that several definitions have been made for example by using include-files.
Assembly code example(1) ldi r16, (1<C example(1) TWCR = (1<Comments
Send START condition
while (!(TWCR & (1<if ((TWSR & 0xF8) != START) ERROR();
152
ATmega406
2548E-AVR-07/06
ATmega406
Assembly code example(1) ldi out r16, SLA_W TWDR, r16 C example(1) TWDR = SLA_W; TWCR = (1<ldi r16, (1<while (!(TWCR & (1<if ((TWSR & 0xF8) != MT_SLA_ACK) ERROR();
TWDR = DATA; TWCR = (1<while (!(TWCR & (1<Wait for TWINT flag set. This indicates that the DATA has been transmitted, and ACK/NACK has been received. Check value of TWI Status Register. Mask prescaler bits. If status different from MT_DATA_ACK go to ERROR
if ((TWSR & 0xF8) != MT_DATA_ACK) ERROR();
TWCR = (1<1. See "About Code Examples" on page 7.
25.8
Transmission Modes
The TWI can operate in one of four major modes. These are named Master Transmitter (MT), Master Receiver (MR), Slave Transmitter (ST) and Slave Receiver (SR). Several of these modes can be used in the same application. As an example, the TWI can use MT mode to write data into a TWI EEPROM, MR mode to read the data back from the EEPROM. If other masters are present in the system, some of these might transmit data to the TWI, and then SR mode would be used. It is the application software that decides which modes are legal. The following sections describe each of these modes. Possible status codes are described along with figures detailing data transmission in each of the modes. These figures contain the following abbreviations:
153
2548E-AVR-07/06
S: Rs: R: W: A: A: Data: P: SLA:
START condition REPEATED START condition Read bit (high level at SDA) Write bit (low level at SDA) Acknowledge bit (low level at SDA) Not acknowledge bit (high level at SDA) 8-bit data byte STOP condition Slave Address
In Figure 25-13 to Figure 25-19, circles are used to indicate that the TWINT flag is set. The numbers in the circles show the status code held in TWSR, with the prescaler bits masked to zero. At these points, actions must be taken by the application to continue or complete the TWI transfer. The TWI transfer is suspended until the TWINT flag is cleared by software. When the TWINT flag is set, the status code in TWSR is used to determine the appropriate software action. For each status code, the required software action and details of the following serial transfer are given in Table 25-3 to Table 25-6. Note that the prescaler bits are masked to zero in these tables. 25.8.1 Master Transmitter Mode In the Master Transmitter mode, a number of data bytes are transmitted to a slave receiver (see Figure 25-12). In order to enter a Master mode, a START condition must be transmitted. The format of the following address packet determines whether Master Transmitter or Master Receiver mode is to be entered. If SLA+W is transmitted, MT mode is entered, if SLA+R is transmitted, MR mode is entered. All the status codes mentioned in this section assume that the prescaler bits are zero or are masked to zero. Figure 25-12. Data Transfer in Master Transmitter Mode
VBUS
Device 1
MASTER TRANSMITTER
Device 2
SLAVE RECEIVER
Device 3
........
Device n
R1
R2
SDA
SCL
154
ATmega406
2548E-AVR-07/06
ATmega406
A START condition is sent by writing the following value to TWCR:
TWCR Value TWINT 1 TWEA X TWSTA 1 TWSTO 0 TWWC X TWEN 1 - 0 TWIE X
TWEN must be set to enable the Two-wire Serial Interface, TWSTA must be written to one to transmit a START condition and TWINT must be written to one to clear the TWINT flag. The TWI will then test the Two-wire Serial Bus and generate a START condition as soon as the bus becomes free. After a START condition has been transmitted, the TWINT flag is set by hardware, and the status code in TWSR will be 0x08 (see Table 25-3). In order to enter MT mode, SLA+W must be transmitted. This is done by writing SLA+W to TWDR. Thereafter the TWINT bit should be cleared (by writing it to one) to continue the transfer. This is accomplished by writing the following value to TWCR:
TWCR Value TWINT 1 TWEA X TWSTA 0 TWSTO 0 TWWC X TWEN 1 - 0 TWIE X
When SLA+W have been transmitted and an acknowledgment bit has been received, TWINT is set again and a number of status codes in TWSR are possible. Possible status codes in Master mode are 0x18, 0x20, or 0x38. The appropriate action to be taken for each of these status codes is detailed in Table 25-3. When SLA+W has been successfully transmitted, a data packet should be transmitted. This is done by writing the data byte to TWDR. TWDR must only be written when TWINT is high. If not, the access will be discarded, and the Write Collision bit (TWWC) will be set in the TWCR Register. After updating TWDR, the TWINT bit should be cleared (by writing it to one) to continue the transfer. This is accomplished by writing the following value to TWCR:
TWCR Value TWINT 1 TWEA X TWSTA 0 TWSTO 0 TWWC X TWEN 1 - 0 TWIE X
This scheme is repeated until the last byte has been sent and the transfer is ended by generating a STOP condition or a repeated START condition. A STOP condition is generated by writing the following value to TWCR:
TWCR Value TWINT 1 TWEA X TWSTA 0 TWSTO 1 TWWC X TWEN 1 - 0 TWIE X
A REPEATED START condition is generated by writing the following value to TWCR:
TWCR Value TWINT 1 TWEA X TWSTA 1 TWSTO 0 TWWC X TWEN 1 - 0 TWIE X
After a repeated START condition (state 0x10) the Two-wire Serial Interface can access the same slave again, or a new slave without transmitting a STOP condition. Repeated START enables the master to switch between slaves, Master Transmitter mode and Master Receiver mode without losing control of the bus.
155
2548E-AVR-07/06
Table 25-3.
Status Code (TWSR) Prescaler Bits are 0 0x08 0x10
Status Codes for Master Transmitter Mode
Application Software Response Status of the Two-wire Serial Bus and Two-wire Serial Interface Hardware A START condition has been transmitted A repeated START condition has been transmitted To TWCR To/from TWDR Load SLA+W Load SLA+W or Load SLA+R STA X X X 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 STO 0 0 0 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 TWINT 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 TWEA X X X X X X X X X X X X X X X X X X X X X Next Action Taken by TWI Hardware SLA+W will be transmitted; ACK or NOT ACK will be received SLA+W will be transmitted; ACK or NOT ACK will be received SLA+R will be transmitted; Logic will switch to Master Receiver mode Data byte will be transmitted and ACK or NOT ACK will be received Repeated START will be transmitted STOP condition will be transmitted and TWSTO flag will be reset STOP condition followed by a START condition will be transmitted and TWSTO flag will be reset Data byte will be transmitted and ACK or NOT ACK will be received Repeated START will be transmitted STOP condition will be transmitted and TWSTO flag will be reset STOP condition followed by a START condition will be transmitted and TWSTO flag will be reset Data byte will be transmitted and ACK or NOT ACK will be received Repeated START will be transmitted STOP condition will be transmitted and TWSTO flag will be reset STOP condition followed by a START condition will be transmitted and TWSTO flag will be reset Data byte will be transmitted and ACK or NOT ACK will be received Repeated START will be transmitted STOP condition will be transmitted and TWSTO flag will be reset STOP condition followed by a START condition will be transmitted and TWSTO flag will be reset Two-wire Serial Bus will be released and not addressed slave mode entered A START condition will be transmitted when the bus becomes free
0x18
SLA+W has been transmitted; ACK has been received
Load data byte or No TWDR action or No TWDR action or No TWDR action
0x20
SLA+W has been transmitted; NOT ACK has been received
Load data byte or No TWDR action or No TWDR action or No TWDR action
0x28
Data byte has been transmitted; ACK has been received
Load data byte or No TWDR action or No TWDR action or No TWDR action
0x30
Data byte has been transmitted; NOT ACK has been received
Load data byte or No TWDR action or No TWDR action or No TWDR action
0x38
Arbitration lost in SLA+W or data bytes
No TWDR action or No TWDR action
156
ATmega406
2548E-AVR-07/06
ATmega406
Figure 25-13. Formats and States in the Master Transmitter Mode
MT
Successfull transmission to a slave receiver
S
SLA
W
A
DATA
A
P
$08
Next transfer started with a repeated start condition
$18
$28
RS
SLA
W
$10
Not acknowledge received after the slave address
A
P
R
$20
MR
Not acknowledge received after a data byte
A
P
$30
Arbitration lost in slave address or data byte
A or A
Other master continues
A or A
Other master continues
$38
Arbitration lost and addressed as slave
$38
Other master continues
A
$68
$78
$B0
To corresponding states in slave mode
From master to slave
DATA
A
Any number of data bytes and their associated acknowledge bits This number (contained in TWSR) corresponds to a defined state of the Two-wire Serial Bus. The prescaler bits are zero or masked to zero
From slave to master
n
25.8.2
Master Receiver Mode In the Master Receiver mode, a number of data bytes are received from a slave transmitter (see Figure 25-14). In order to enter a Master mode, a START condition must be transmitted. The format of the following address packet determines whether Master Transmitter or Master Receiver mode is to be entered. If SLA+W is transmitted, MT mode is entered, if SLA+R is transmitted, MR mode is entered. All the status codes mentioned in this section assume that the prescaler bits are zero or are masked to zero.
157
2548E-AVR-07/06
Figure 25-14. Data Transfer in Master Receiver Mode
VBUS
Device 1
MASTER RECEIVER
Device 2
SLAVE TRANSMITTER
Device 3
........
Device n
R1
R2
SDA
SCL
A START condition is sent by writing the following value to TWCR:
TWCR Value TWINT 1 TWEA X TWSTA 1 TWSTO 0 TWWC X TWEN 1 - 0 TWIE X
TWEN must be written to one to enable the Two-wire Serial Interface, TWSTA must be written to one to transmit a START condition and TWINT must be set to clear the TWINT flag. The TWI will then test the Two-wire Serial Bus and generate a START condition as soon as the bus becomes free. After a START condition has been transmitted, the TWINT flag is set by hardware, and the status code in TWSR will be 0x08 (see Table 25-3). In order to enter MR mode, SLA+R must be transmitted. This is done by writing SLA+R to TWDR. Thereafter the TWINT bit should be cleared (by writing it to one) to continue the transfer. This is accomplished by writing the following value to TWCR:
TWCR Value TWINT 1 TWEA X TWSTA 0 TWSTO 0 TWWC X TWEN 1 - 0 TWIE X
When SLA+R have been transmitted and an acknowledgment bit has been received, TWINT is set again and a number of status codes in TWSR are possible. Possible status codes in Master mode are 0x38, 0x40, or 0x48. The appropriate action to be taken for each of these status codes is detailed in Table 25-13. Received data can be read from the TWDR Register when the TWINT flag is set high by hardware. This scheme is repeated until the last byte has been received. After the last byte has been received, the MR should inform the ST by sending a NACK after the last received data byte. The transfer is ended by generating a STOP condition or a repeated START condition. A STOP condition is generated by writing the following value to TWCR:
TWCR Value TWINT 1 TWEA X TWSTA 0 TWSTO 1 TWWC X TWEN 1 - 0 TWIE X
A REPEATED START condition is generated by writing the following value to TWCR:
TWCR Value TWINT 1 TWEA X TWSTA 1 TWSTO 0 TWWC X TWEN 1 - 0 TWIE X
After a repeated START condition (state 0x10) the Two-wire Serial Interface can access the same slave again, or a new slave without transmitting a STOP condition. Repeated START
158
ATmega406
2548E-AVR-07/06
ATmega406
enables the master to switch between slaves, Master Transmitter mode and Master Receiver mode without losing control over the bus. Table 25-4.
Status Code (TWSR) Prescaler Bits are 0 0x08 0x10
Status Codes for Master Receiver Mode
Application Software Response Status of the Two-wire Serial Bus and Two-wire Serial Interface Hardware A START condition has been transmitted A repeated START condition has been transmitted To TWCR To/from TWDR Load SLA+R Load SLA+R or Load SLA+W STA X X X 0 1 0 0 1 0 1 0 0 1 0 1 STO 0 0 0 0 0 0 0 0 1 1 0 0 0 1 1 TWINT 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 TWEA X X X X X 0 1 X X X 0 1 X X X Next Action Taken by TWI Hardware SLA+R will be transmitted ACK or NOT ACK will be received SLA+R will be transmitted ACK or NOT ACK will be received SLA+W will be transmitted Logic will switch to Master Transmitter mode Two-wire Serial Bus will be released and not addressed Slave mode will be entered A START condition will be transmitted when the bus becomes free Data byte will be received and NOT ACK will be returned Data byte will be received and ACK will be returned Repeated START will be transmitted STOP condition will be transmitted and TWSTO flag will be reset STOP condition followed by a START condition will be transmitted and TWSTO flag will be reset Data byte will be received and NOT ACK will be returned Data byte will be received and ACK will be returned Repeated START will be transmitted STOP condition will be transmitted and TWSTO flag will be reset STOP condition followed by a START condition will be transmitted and TWSTO flag will be reset
0x38
Arbitration lost in SLA+R or NOT ACK bit
No TWDR action or No TWDR action
0x40
SLA+R has been transmitted; ACK has been received SLA+R has been transmitted; NOT ACK has been received
No TWDR action or No TWDR action
0x48
No TWDR action or No TWDR action or No TWDR action
0x50
Data byte has been received; ACK has been returned Data byte has been received; NOT ACK has been returned
Read data byte or Read data byte
0x58
Read data byte or Read data byte or Read data byte
159
2548E-AVR-07/06
Figure 25-15. Formats and States in the Master Receiver Mode
MR
Successfull reception from a slave receiver
S
SLA
R
A
DATA
A
DATA
A
P
$08
Next transfer started with a repeated start condition
$40
$50
$58
RS
SLA
R
$10
Not acknowledge received after the slave address
A
P
W
$48
MT
Arbitration lost in slave address or data byte
A or A
Other master continues
A
Other master continues
$38
Arbitration lost and addressed as slave
$38
Other master continues
A
$68
$78
$B0
To corresponding states in slave mode
From master to slave
DATA
A
Any number of data bytes and their associated acknowledge bits This number (contained in TWSR) corresponds to a defined state of the Two-wire Serial Bus. The prescaler bits are zero or masked to zero
From slave to master
n
25.8.3
Slave Receiver Mode In the Slave Receiver mode, a number of data bytes are received from a master transmitter (see Figure 25-16). All the status codes mentioned in this section assume that the prescaler bits are zero or are masked to zero. Figure 25-16. Data Transfer in Slave Receiver Mode
VBUS
Device 1
SLAVE RECEIVER
Device 2
MASTER TRANSMITTER
Device 3
........
Device n
R1
R2
SDA
SCL
To initiate the Slave Receiver mode, TWAR and TWCR must be initialized as follows:
160
ATmega406
2548E-AVR-07/06
ATmega406
TWAR Value TWA6 TWA5 TWA4 TWA3 TWA2 TWA1 TWA0 TWGCE
Device's Own Slave Address
The upper seven bits are the address to which the Two-wire Serial Interface will respond when addressed by a master. If the LSB is set, the TWI will respond to the general call address (0x00), otherwise it will ignore the general call address.
TWCR Value TWINT 0 TWEA 1 TWSTA 0 TWSTO 0 TWWC 0 TWEN 1 - 0 TWIE X
TWEN must be written to one to enable the TWI. The TWEA bit must be written to one to enable the acknowledgment of the device's own slave address or the general call address. TWSTA and TWSTO must be written to zero. When TWAR and TWCR have been initialized, the TWI waits until it is addressed by its own slave address (or the general call address if enabled) followed by the data direction bit. If the direction bit is "0" (write), the TWI will operate in SR mode, otherwise ST mode is entered. After its own slave address and the write bit have been received, the TWINT flag is set and a valid status code can be read from TWSR. The status code is used to determine the appropriate software action. The appropriate action to be taken for each status code is detailed in Table 25-5. The Slave Receiver mode may also be entered if arbitration is lost while the TWI is in the Master mode (see states 0x68 and 0x78). If the TWEA bit is reset during a transfer, the TWI will return a "Not Acknowledge" ("1") to SDA after the next received data byte. This can be used to indicate that the slave is not able to receive any more bytes. While TWEA is zero, the TWI does not acknowledge its own slave address. However, the Two-wire Serial Bus is still monitored and address recognition may resume at any time by setting TWEA. This implies that the TWEA bit may be used to temporarily isolate the TWI from the Two-wire Serial Bus. In all sleep modes other than Idle mode, the clock system to the TWI is turned off. If the TWEA bit is set, the interface can still acknowledge its own slave address or the general call address by using the Two-wire Serial Bus clock as a clock source. The part will then wake-up from sleep and the TWI will hold the SCL clock low during the wake up and until the TWINT flag is cleared (by writing it to one). Further data reception will be carried out as normal, with the AVR clocks running as normal. Observe that if the AVR is set up with a long start-up time, the SCL line may be held low for a long time, blocking other data transmissions. Note that the Two-wire Serial Interface Data Register - TWDR does not reflect the last byte present on the bus when waking up from these Sleep modes.
161
2548E-AVR-07/06
Table 25-5.
Status Code (TWSR) Prescaler Bits Are 0 0x60
Status Codes for Slave Receiver Mode
Application Software Response Status of the Two-wire Serial Bus and Two-wire Serial Interface Hardware Own SLA+W has been received; ACK has been returned Arbitration lost in SLA+R/W as master; own SLA+W has been received; ACK has been returned General call address has been received; ACK has been returned Arbitration lost in SLA+R/W as master; General call address has been received; ACK has been returned Previously addressed with own SLA+W; data has been received; ACK has been returned Previously addressed with own SLA+W; data has been received; NOT ACK has been returned To TWCR To/from TWDR No TWDR action or No TWDR action STA X X X X X X X X X X 0 0 STO 0 0 0 0 0 0 0 0 0 0 0 0 TWINT 1 1 1 1 1 1 1 1 1 1 1 1 TWEA 0 1 0 1 0 1 0 1 0 1 0 1 Next Action Taken by TWI Hardware Data byte will be received and NOT ACK will be returned Data byte will be received and ACK will be returned Data byte will be received and NOT ACK will be returned Data byte will be received and ACK will be returned Data byte will be received and NOT ACK will be returned Data byte will be received and ACK will be returned Data byte will be received and NOT ACK will be returned Data byte will be received and ACK will be returned Data byte will be received and NOT ACK will be returned Data byte will be received and ACK will be returned Switched to the not addressed Slave mode; no recognition of own SLA or GCA Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1" Switched to the not addressed Slave mode; no recognition of own SLA or GCA; a START condition will be transmitted when the bus becomes free Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1"; a START condition will be transmitted when the bus becomes free Data byte will be received and NOT ACK will be returned Data byte will be received and ACK will be returned Switched to the not addressed Slave mode; no recognition of own SLA or GCA Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1" Switched to the not addressed Slave mode; no recognition of own SLA or GCA; a START condition will be transmitted when the bus becomes free Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1"; a START condition will be transmitted when the bus becomes free Switched to the not addressed Slave mode; no recognition of own SLA or GCA Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1" Switched to the not addressed Slave mode; no recognition of own SLA or GCA; a START condition will be transmitted when the bus becomes free Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1"; a START condition will be transmitted when the bus becomes free
0x68
No TWDR action or No TWDR action No TWDR action or No TWDR action
0x70
0x78
No TWDR action or No TWDR action Read data byte or Read data byte Read data byte or Read data byte or
0x80
0x88
Read data byte or
1
0
1
0
Read data byte
1
0
1
1
0x90
Previously addressed with general call; data has been received; ACK has been returned Previously addressed with general call; data has been received; NOT ACK has been returned
Read data byte or Read data byte Read data byte or Read data byte or
X X 0 0
0 0 0 0
1 1 1 1
0 1 0 1
0x98
Read data byte or
1
0
1
0
Read data byte
1
0
1
1
0xA0
A STOP condition or repeated START condition has been received while still addressed as slave
Read data byte or Read data byte or
0 0
0 0
1 1
0 1
Read data byte or
1
0
1
0
Read data byte
1
0
1
1
162
ATmega406
2548E-AVR-07/06
ATmega406
Figure 25-17. Formats and States in the Slave Receiver Mode
Reception of the own slave address and one or more data bytes. All are acknowledged
S
SLA
W
A
DATA
A
DATA
A
P or S
$60
Last data byte received is not acknowledged
$80
$80
$A0
A
P or S
$88
Arbitration lost as master and addressed as slave
A
$68
Reception of the general call address and one or more data bytes
General Call
A
DATA
A
DATA
A
P or S
$70
Last data byte received is not acknowledged
$90
$90
$A0
A
P or S
$98
Arbitration lost as master and addressed as slave by general call
A
$78
From master to slave
DATA
A
Any number of data bytes and their associated acknowledge bits This number (contained in TWSR) corresponds to a defined state of the Two-wire Serial Bus. The prescaler bits are zero or masked to zero
From slave to master
n
163
2548E-AVR-07/06
25.8.4
Slave Transmitter Mode In the Slave Transmitter mode, a number of data bytes are transmitted to a master receiver (see Figure 25-18). All the status codes mentioned in this section assume that the prescaler bits are zero or are masked to zero. Figure 25-18. Data Transfer in Slave Transmitter Mode
VBUS
Device 1
SLAVE TRANSMITTER
Device 2
MASTER RECEIVER
Device 3
........
Device n
R1
R2
SDA
SCL
To initiate the Slave Transmitter mode, TWAR and TWCR must be initialized as follows:
TWAR Value TWA6 TWA5 TWA4 TWA3 TWA2 TWA1 TWA0 TWGCE Device's Own Slave Address
The upper seven bits are the address to which the Two-wire Serial Interface will respond when addressed by a master. If the LSB is set, the TWI will respond to the general call address (0x00), otherwise it will ignore the general call address.
TWCR Value TWINT 0 TWEA 1 TWSTA 0 TWSTO 0 TWWC 0 TWEN 1 - 0 TWIE X
TWEN must be written to one to enable the TWI. The TWEA bit must be written to one to enable the acknowledgment of the device's own slave address or the general call address. TWSTA and TWSTO must be written to zero. When TWAR and TWCR have been initialized, the TWI waits until it is addressed by its own slave address (or the general call address if enabled) followed by the data direction bit. If the direction bit is "1" (read), the TWI will operate in ST mode, otherwise SR mode is entered. After its own slave address and the write bit have been received, the TWINT flag is set and a valid status code can be read from TWSR. The status code is used to determine the appropriate software action. The appropriate action to be taken for each status code is detailed in Table 25-6. The Slave Transmitter mode may also be entered if arbitration is lost while the TWI is in the Master mode (see state 0xB0). If the TWEA bit is written to zero during a transfer, the TWI will transmit the last byte of the transfer. State 0xC0 or state 0xC8 will be entered, depending on whether the master receiver transmits a NACK or ACK after the final byte. The TWI is switched to the not addressed Slave mode, and will ignore the master if it continues the transfer. Thus the master receiver receives all "1" as serial data. State 0xC8 is entered if the master demands additional data bytes (by transmitting ACK), even though the slave has transmitted the last byte (TWEA zero and expecting NACK from the master). 164
ATmega406
2548E-AVR-07/06
ATmega406
While TWEA is zero, the TWI does not respond to its own slave address. However, the Two-wire Serial Bus is still monitored and address recognition may resume at any time by setting TWEA. This implies that the TWEA bit may be used to temporarily isolate the TWI from the Two-wire Serial Bus. In all sleep modes other than Idle mode, the clock system to the TWI is turned off. If the TWEA bit is set, the interface can still acknowledge its own slave address or the general call address by using the Two-wire Serial Bus clock as a clock source. The part will then wake up from sleep and the TWI will hold the SCL clock will low during the wake up and until the TWINT flag is cleared (by writing it to one). Further data transmission will be carried out as normal, with the AVR clocks running as normal. Observe that if the AVR is set up with a long start-up time, the SCL line may be held low for a long time, blocking other data transmissions. Note that the Two-wire Serial Interface Data Register - TWDR - does not reflect the last byte present on the bus when waking up from these sleep modes. Table 25-6.
Status Code (TWSR) Prescaler Bits are 0 0xA8
Status Codes for Slave Transmitter Mode
Application Software Response Status of the Two-wire Serial Bus and Two-wire Serial Interface Hardware Own SLA+R has been received; ACK has been returned To TWCR To/from TWDR Load data byte or Load data byte STA X X X X X X 0 0 STO 0 0 0 0 0 0 0 0 TWINT 1 1 1 1 1 1 1 1 TWEA 0 1 0 1 0 1 0 1 Next Action Taken by TWI Hardware Last data byte will be transmitted and NOT ACK should be received Data byte will be transmitted and ACK should be received Last data byte will be transmitted and NOT ACK should be received Data byte will be transmitted and ACK should be received Last data byte will be transmitted and NOT ACK should be received Data byte will be transmitted and ACK should be received Switched to the not addressed Slave mode; no recognition of own SLA or GCA Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1" Switched to the not addressed Slave mode; no recognition of own SLA or GCA; a START condition will be transmitted when the bus becomes free Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1"; a START condition will be transmitted when the bus becomes free Switched to the not addressed Slave mode; no recognition of own SLA or GCA Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1" Switched to the not addressed Slave mode; no recognition of own SLA or GCA; a START condition will be transmitted when the bus becomes free Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1"; a START condition will be transmitted when the bus becomes free
0xB0
Arbitration lost in SLA+R/W as master; own SLA+R has been received; ACK has been returned Data byte in TWDR has been transmitted; ACK has been received Data byte in TWDR has been transmitted; NOT ACK has been received
Load data byte or Load data byte Load data byte or Load data byte No TWDR action or No TWDR action or
0xB8
0xC0
No TWDR action or
1
0
1
0
No TWDR action
1
0
1
1
0xC8
Last data byte in TWDR has been transmitted (TWEA = "0"); ACK has been received
No TWDR action or No TWDR action or
0 0
0 0
1 1
0 1
No TWDR action or
1
0
1
0
No TWDR action
1
0
1
1
165
2548E-AVR-07/06
Figure 25-19. Formats and States in the Slave Transmitter Mode
Reception of the own slave address and one or more data bytes
S
SLA
R
A
DATA
A
DATA
A
P or S
$A8
Arbitration lost as master and addressed as slave
$B8
$C0
A
$B0
Last data byte transmitted. Switched to not addressed slave (TWEA = '0')
A
All 1's
P or S
$C8
From master to slave
DATA
A
Any number of data bytes and their associated acknowledge bits This number (contained in TWSR) corresponds to a defined state of the Two-wire Serial Bus. The prescaler bits are zero or masked to zero
From slave to master
n
25.8.5
Miscellaneous States There are two status codes that do not correspond to a defined TWI state, see Table 25-7. Status 0xF8 indicates that no relevant information is available because the TWINT flag is not set. This occurs between other states, and when the TWI is not involved in a serial transfer. Status 0x00 indicates that a bus error has occurred during a Two-wire Serial Bus transfer. A bus error occurs when a START or STOP condition occurs at an illegal position in the format frame. Examples of such illegal positions are during the serial transfer of an address byte, a data byte, or an acknowledge bit. When a bus error occurs, TWINT is set. To recover from a bus error, the TWSTO flag must set and TWINT must be cleared by writing a logic one to it. This causes the TWI to enter the not addressed Slave mode and to clear the TWSTO flag (no other bits in TWCR are affected). The SDA and SCL lines are released, and no STOP condition is transmitted.
166
ATmega406
2548E-AVR-07/06
ATmega406
Table 25-7.
Status Code (TWSR) Prescaler Bits are 0 0xF8 0x00
Miscellaneous States
Application Software Response Status of the Two-wire Serial Bus and Two-wire Serial Interface hardware No relevant state information available; TWINT = "0" Bus error due to an illegal START or STOP condition To TWCR To/from TWDR No TWDR action No TWDR action 0 STA STO TWINT TWEA Next Action Taken by TWI Hardware Wait or proceed current transfer X Only the internal hardware is affected, no STOP condition is sent on the bus. In all cases, the bus is released and TWSTO is cleared.
No TWCR action 1 1
25.8.6
Combining Several TWI Modes In some cases, several TWI modes must be combined in order to complete the desired action. Consider for example reading data from a serial EEPROM. Typically, such a transfer involves the following steps: 1. The transfer must be initiated. 2. The EEPROM must be instructed what location should be read. 3. The reading must be performed. 4. The transfer must be finished. Note that data is transmitted both from Master to Slave and vice versa. The Master must instruct the slave what location it wants to read, requiring the use of the MT mode. Subsequently, data must be read from the slave, implying the use of the MR mode. Thus, the transfer direction must be changed. The Master must keep control of the bus during all these steps, and the steps should be carried out as an atomic operation. If this principle is violated in a multi-master system, another master can alter the data pointer in the EEPROM between steps 2 and 3, and the master will read the wrong data location. Such a change in transfer direction is accomplished by transmitting a REPEATED START between the transmission of the address byte and reception of the data. After a REPEATED START, the master keeps ownership of the bus. The following figure shows the flow in this transfer. Figure 25-20. Combining Several TWI Modes to Access a Serial EEPROM
Master Transmitter Master Receiver
S
SLA+W
A
ADDRESS
A
Rs
SLA+R
A
DATA
A
P
S = START Transmitted from master to slave
Rs = REPEATED START Transmitted from slave to master
P = STOP
25.9
Multi-master Systems and Arbitration
If multiple masters are connected to the same bus, transmissions may be initiated simultaneously by one or more of them. The TWI standard ensures that such situations are handled in such a way that one of the masters will be allowed to proceed with the transfer, and that no data will be lost in the process. An example of an arbitration situation is depicted below, where two masters are trying to transmit data to a slave receiver.
167
2548E-AVR-07/06
Figure 25-21. An Arbitration Example
VBUS
Device 1
MASTER TRANSMITTER
Device 2
MASTER TRANSMITTER
Device 3
SLAVE RECEIVER
........
Device n
R1
R2
SDA
SCL
Several different scenarios may arise during arbitration, as described below: * Two or more masters are performing identical communication with the same slave. In this case, neither the slave nor any of the masters will know about the bus contention. * Two or more masters are accessing the same slave with different data or direction bit. In this case, arbitration will occur, either in the READ/WRITE bit or in the data bits. The masters trying to output a one on SDA while another master outputs a zero will lose the arbitration. Losing masters will switch to not addressed Slave mode or wait until the bus is free and transmit a new START condition, depending on application software action. * Two or more masters are accessing different slaves. In this case, arbitration will occur in the SLA bits. Masters trying to output a one on SDA while another master outputs a zero will lose the arbitration. Masters losing arbitration in SLA will switch to Slave mode to check if they are being addressed by the winning master. If addressed, they will switch to SR or ST mode, depending on the value of the READ/WRITE bit. If they are not being addressed, they will switch to not addressed Slave mode or wait until the bus is free and transmit a new START condition, depending on application software action. This is summarized in Figure 25-22. Possible status values are given in circles. Figure 25-22. Possible Status Codes Caused by Arbitration
START SLA Data STOP
Arbitration lost in SLA
Arbitration lost in Data
Own Address / General Call received
No
38
TWI bus will be released and not addressed slave mode will be entered A START condition will be transmitted when the bus becomes free
Yes Write 68/78
Data byte will be received and NOT ACK will be returned Data byte will be received and ACK will be returned
Direction
Read B0
Last data byte will be transmitted and NOT ACK should be received Data byte will be transmitted and ACK should be received
168
ATmega406
2548E-AVR-07/06
ATmega406
25.10 Bus Connect/Disconnect for Two-wire Serial Interface
The Bus Connect/Disconnect module is an addition to the TWI Interface. Based on a configuration bit, an interrupt can be generated either when the TWI bus is connected or disconnected. Figure 25-23 illustrates the Bus Connect/Disconnect logic, where SDA and SCL are the TWI data and clock lines, respectively. When the TWI bus is connected, both the SDA and the SCL lines will become high simultaneously. If the TWBCIP bit is cleared, the interrupt will be executed if enabled. Once the bus is connected, the TWBCIP bit should be set. This enables detection of when the bus is disconnected, and prevents repetitive interrupts every time both the SDA and SCL lines are high (e.g. bus IDLE state). When the TWI bus is disconnected, both the SDA and the SCL lines will become low simultaneously. If the TWBCIP bit is set, the interrupt will be executed if enabled and if both lines remain low for a configurable time period. By adding this time constraint, unwanted interrupts caused by both lines going low during normal bus communication is prevented. Figure 25-23. Overview of Bus Connect/Disconnect.
SCL SDA DELAY ELEMENT START DELAY OUTPUT
TWBCIP
TWBDT
SET TWBCIF
TWBCSR
IRQ
8-BIT DATA BUS
25.10.1
TWBCSR - TWI Bus Control and Status Register
Bit (0xBE) Read/Write Initial Value 7 TWBCIF R/W X 6 TWBCIE R/W 0 5 - R 0 4 - R 0 3 - R 0 2 TWBDT1 R/W 0 1 TWBDT0 R/W 0 0 TWBCIP R/W 0 TWBCSR
* Bit 7 - TWBCIF: TWI Bus Connect/Disconnect Interrupt Flag Based on the TWBCIP bit, the TWBCIF bit is set when the TWI bus is connected or disconnected. TWBCIF is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, TWBCIF is cleared by writing a logic one to the flag. When the SREG I-bit, TWBCIE (TWI Bus Connect/Disconnect Interrupt Enable), and TWBCIF are set, the TWI Bus
169
2548E-AVR-07/06
Connect/Disconnect Interrupt is executed. If both SDA and SCL are high during reset, TWBCIF will be set after reset. Otherwise TWBCIF will be cleared after reset. * Bit 6 - TWBCIE: TWI Bus Connect/Disconnect Interrupt Enable When the TWBCIE bit and the I-bit in the Status Register are set, the TWI Bus Connect/Disconne ct In terr upt is e nab le d. Th e corre spon ding inte rrup t is execu ted if a TWI Bus Connect/Disconnect occurs, i.e., when the TWBCIE bit is set. * Bit 5:3 - Res: Reserved Bits These bits are reserved bits in the ATmega406 and will always read as zero. * Bit 2:1 - TWBDT1, TWBDT0: TWI Bus Disconnect Time-out Period The TWBDT bits decides how long both the TWI data (SDA) and clock (SCL) signals must be low before generating the TWI Bus Disconnect Interrupt. The different configuration values and their corresponding time-out periods are shown in Table 25-8.
Table 25-8.
TWBDT1 0 0 1 1
TW Bus Disconnect Time-out Period
TWBDT0 0 1 0 1 TWI Bus Disconnect Time-out Period 250 ms 500 ms 1000 ms 2000 ms
* Bit 0 - TWBCIP: TWI Bus Connect/Disconnect Interrupt Polarity The TWBCIP bit decide if the TWI Bus Connect/Disconnect Interrupt Flag (TWBCIF) should be set on a Bus Connect or a Bus Disconnect. If TWBCIP is cleared, the TWBCIF flag is set on a Bus Connect. If TWBCIP is set, the TWBCIF flag is set on a Bus Disconnect.
170
ATmega406
2548E-AVR-07/06
ATmega406
26. JTAG Interface and On-chip Debug System
26.1 Features
* JTAG (IEEE std. 1149.1 Compliant) Interface * Debugger Access to:
- All Internal Peripheral Units - Internal and External RAM - The Internal Register File - Program Counter - EEPROM and Flash Memories * Extensive On-chip Debug Support for Break Conditions, Including - AVR Break Instruction - Break on Change of Program Memory Flow - Single Step Break - Program Memory Break Points on Single Address or Address Range - Data Memory Break Points on Single Address or Address Range * Programming of Flash, EEPROM, Fuses, and Lock Bits through the JTAG Interface * On-chip Debugging Supported by AVR Studio(R)
26.2
Overview
The AVR IEEE std. 1149.1 compliant JTAG interface can be used for * Programming the non-volatile memories, Fuses and Lock bits * On-chip debugging A brief description is given in the following sections. Detailed descriptions for Programming via the JTAG interface can be found in the section "Programming via the JTAG Interface" on page 211. The On-chip Debug support is considered being private JTAG instructions, and distributed within ATMEL and to selected third party vendors only. Figure 26-1 shows a block diagram of the JTAG interface and the On-chip Debug system. The TAP Controller is a state machine controlled by the TCK and TMS signals. The TAP Controller selects either the JTAG Instruction Register or one of several Data Registers as the scan chain (Shift Register) between the TDI - input and TDO - output. The Instruction Register holds JTAG instructions controlling the behavior of a Data Register. The JTAG Programming Interface (actually consisting of several physical and virtual Data Registers) is used for serial programming via the JTAG interface. The Internal Scan Chain and Break Point Scan Chain are used for On-chip debugging only.
26.3
Test Access Port - TAP
The JTAG interface is accessed through four of the AVR's pins. In JTAG terminology, these pins constitute the Test Access Port - TAP. These pins are: * TMS: Test mode select. This pin is used for navigating through the TAP-controller state machine. * TCK: Test Clock. JTAG operation is synchronous to TCK. * TDI: Test Data In. Serial input data to be shifted in to the Instruction Register or Data Register (Scan Chains). * TDO: Test Data Out. Serial output data from Instruction Register or Data Register.
171
2548E-AVR-07/06
The IEEE std. 1149.1 also specifies an optional TAP signal; TRST - Test ReSeT - which is not provided. When the JTAGEN Fuse is unprogrammed, these four TAP pins are normal port pins, and the TAP controller is in reset. When programmed, the input TAP signals are internally pulled high and the JTAG is enabled for programming. The device is shipped with this fuse programmed. For the On-chip Debug system, in addition to the JTAG interface pins, the RESET pin is monitored by the debugger to be able to detect external reset sources. The debugger can also pull the RESET pin low to reset the whole system, assuming only open collectors on the reset line are used in the application. Figure 26-1. Block Diagram
TDI TDO TCK TMS
TAP CONTROLLER
JTAG PROGRAMMING INTERFACE
AVR CPU INSTRUCTION REGISTER ID REGISTER M U X BYPASS REGISTER FLASH MEMORY Address Data INTERNAL SCAN CHAIN PC Instruction
BREAKPOINT UNIT
FLOW CONTROL UNIT DIGITAL PERIPHERAL UNITS
BREAKPOINT SCAN CHAIN ADDRESS DECODER JTAG / AVR CORE COMMUNICATION INTERFACE
OCD STATUS AND CONTROL
172
ATmega406
2548E-AVR-07/06
ATmega406
Figure 26-2. TAP Controller State Diagram
1 Test-Logic-Reset 0 0 Run-Test/Idle 1 Select-DR Scan 0 1 Capture-DR 0 Shift-DR 1 Exit1-DR 0 Pause-DR 1 0 Exit2-DR 1 Update-DR 1 0 0 0 1 0 1 1 Select-IR Scan 0 Capture-IR 0 Shift-IR 1 Exit1-IR 0 Pause-IR 1 Exit2-IR 1 Update-IR 1 0 0 1 0 1
26.4
TAP Controller
The TAP controller is a 16-state finite state machine that controls the operation of the JTAG programming circuitry, or On-chip Debug system. The state transitions depicted in Figure 26-2 depend on the signal present on TMS (shown adjacent to each state transition) at the time of the rising edge at TCK. The initial state after a Power-on Reset is Test-Logic-Reset. As a definition in this document, the LSB is shifted in and out first for all Shift Registers. Assuming Run-Test/Idle is the present state, a typical scenario for using the JTAG interface is: * At the TMS input, apply the sequence 1, 1, 0, 0 at the rising edges of TCK to enter the Shift Instruction Register - Shift-IR state. While in this state, shift the four bits of the JTAG instructions into the JTAG Instruction Register from the TDI input at the rising edge of TCK. The TMS input must be held low during input of the 3 LSBs in order to remain in the Shift-IR state. The MSB of the instruction is shifted in when this state is left by setting TMS high. While the instruction is shifted in from the TDI pin, the captured IR-state 0x01 is shifted out on the TDO pin. The JTAG Instruction selects a particular Data Register as path between TDI and TDO and controls the circuitry surrounding the selected Data Register.
173
2548E-AVR-07/06
* Apply the TMS sequence 1, 1, 0 to re-enter the Run-Test/Idle state. The instruction is latched onto the parallel output from the Shift Register path in the Update-IR state. The Exit-IR, PauseIR, and Exit2-IR states are only used for navigating the state machine. * At the TMS input, apply the sequence 1, 0, 0 at the rising edges of TCK to enter the Shift Data Register - Shift-DR state. While in this state, upload the selected data register (selected by the present JTAG instruction in the JTAG Instruction Register) from the TDI input at the rising edge of TCK. In order to remain in the Shift-DR state, the TMS input must be held low during input of all bits except the MSB. The MSB of the data is shifted in when this state is left by setting TMS high. While the data register is shifted in from the TDI pin, the parallel inputs to the data register captured in the Capture-DR state is shifted out on the TDO pin. * Apply the TMS sequence 1, 1, 0 to re-enter the Run-Test/Idle state. If the selected data register has a latched parallel-output, the latching takes place in the Update-DR state. The Exit-DR, Pause-DR, and Exit2-DR states are only used for navigating the state machine. As shown in the state diagram, the Run-Test/Idle state need not be entered between selecting JTAG instruction and using data registers, and some JTAG instructions may select certain functions to be performed in the Run-Test/Idle, making it unsuitable as an Idle state.
Note: Independent of the initial state of the TAP Controller, the Test-Logic-Reset state can always be entered by holding TMS high for five TCK clock periods.
For detailed information on the JTAG specification, refer to the literature listed in "JTAG Interface and On-chip Debug System" on page 171.
26.5
Using the On-chip Debug System
As shown in Figure 26-1, the hardware support for On-chip Debugging consists mainly of * A scan chain on the interface between the internal AVR CPU and the internal peripheral units. * Break Point unit. * Communication interface between the CPU and JTAG system. All read or modify/write operations needed for implementing the Debugger are done by applying AVR instructions via the internal AVR CPU Scan Chain. The CPU sends the result to an I/O memory mapped location which is part of the communication interface between the CPU and the JTAG system. The Break Point Unit implements Break on Change of Program Flow, Single Step Break, two Program Memory Break Points, and two combined Break Points. Together, the four Break Points can be configured as either: * 4 single Program Memory Break Points. * 3 Single Program Memory Break Point + 1 single Data Memory Break Point. * 2 single Program Memory Break Points + 2 single Data Memory Break Points. * 2 single Program Memory Break Points + 1 Program Memory Break Point with mask ("range Break Point"). * 2 single Program Memory Break Points + 1 Data Memory Break Point with mask ("range Break Point"). A debugger, like the AVR Studio, may however use one or more of these resources for its internal purpose, leaving less flexibility to the end-user. A list of the On-chip Debug specific JTAG instructions is given in "On-chip Debug Specific JTAG Instructions" on page 175.
174
ATmega406
2548E-AVR-07/06
ATmega406
The JTAGEN Fuse must be programmed to enable the JTAG Test Access Port. In addition, the OCDEN Fuse must be programmed and no Lock bits must be set for the On-chip debug system to work. As a security feature, the On-chip debug system is disabled when either of the LB1 or LB2 Lock bits are set. Otherwise, the On-chip debug system would have provided a back-door into a secured device. The AVR Studio enables the user to fully control execution of programs on an AVR device with On-chip Debug capability, AVR In-Circuit Emulator, or the built-in AVR Instruction Set Simulator. AVR Studio(R) supports source level execution of Assembly programs assembled with Atmel Corporation's AVR Assembler and C programs compiled with third party vendors' compilers. AVR Studio runs under Microsoft(R) Windows(R) 95/98/2000 and Microsoft Windows NT(R). For a full description of the AVR Studio, please refer to the AVR Studio User Guide. Only highlights are presented in this document. All necessary execution commands are available in AVR Studio, both on source level and on disassembly level. The user can execute the program, single step through the code either by tracing into or stepping over functions, step out of functions, place the cursor on a statement and execute until the statement is reached, stop the execution, and reset the execution target. In addition, the user can have an unlimited number of code Break Points (using the BREAK instruction) and up to two data memory Break Points, alternatively combined as a mask (range) Break Point.
26.6
On-chip Debug Specific JTAG Instructions
The On-chip debug support is considered being private JTAG instructions, and distributed within ATMEL and to selected third party vendors only. Instruction opcodes are listed for reference.
26.6.1
PRIVATE0; 0x8 Private JTAG instruction for accessing On-chip debug system.
26.6.2
PRIVATE1; 0x9 Private JTAG instruction for accessing On-chip debug system.
26.6.3
PRIVATE2; 0xA Private JTAG instruction for accessing On-chip debug system. PRIVATE3; 0xB Private JTAG instruction for accessing On-chip debug system.
26.6.4
175
2548E-AVR-07/06
26.7
26.7.1
On-chip Debug Related Register
OCDR - On-chip Debug Register
Bit 0x31 (0x51) Read/Write Initial Value R/W 0 R/W 0 R/W 0 7 6 5 4 3 2 1 0 OCDR R/W 0 R/W 0 R/W 0
On-Chip Debug Register
R/W 0
R/W 0
The OCDR Register provides a communication channel from the running program in the microcontroller to the debugger. The CPU can transfer a byte to the debugger by writing to this location. At the same time, an internal flag; I/O Debug Register Dirty - IDRD - is set to indicate to the debugger that the register has been written. When the CPU reads the OCDR Register the 7 LSB will be from the OCDR Register, while the MSB is the IDRD bit. The debugger clears the IDRD bit when it has read the information. In some AVR devices, this register is shared with a standard I/O location. In this case, the OCDR Register can only be accessed if the OCDEN Fuse is programmed, and the debugger enables access to the OCDR Register. In all other cases, the standard I/O location is accessed. Refer to the debugger documentation for further information on how to use this register. 26.7.2 MCUCR - MCU Control Register The MCU Control Register contains control bits for general MCU functions.
Bit 0x35 (0x55) Read/Write Initial Value 7 JTD R/W 0 R/W 0 R/W 0 6 5 4 PUD R/W 0 R/W 0 R/W 0 3 2 1 IVSEL R/W 0 0 IVCE R/W 0 MCUCR
* Bit 7 - JTD: JTAG Interface Disable When this bit is zero, the JTAG interface is enabled if the JTAGEN Fuse is programmed. If this bit is one, the JTAG interface is disabled. In order to avoid unintentional disabling or enabling of the JTAG interface, a timed sequence must be followed when changing this bit: The application software must write this bit to the desired value twice within four cycles to change its value. Note that this bit must not be altered when using the On-chip Debug system.
176
ATmega406
2548E-AVR-07/06
ATmega406
26.8 Using the JTAG Programming Capabilities
Programming of AVR parts via JTAG is performed via the 4-pin JTAG port, TCK, TMS, TDI, and TDO. These are the only pins that need to be controlled/observed to perform JTAG programming (in addition to power pins). It is not required to apply 12V externally. The JTAGEN Fuse must be programmed and the JTD bit in the MCUCR Register must be cleared to enable the JTAG Test Access Port. The JTAG programming capability supports: * Flash programming and verifying. * EEPROM programming and verifying. * Fuse programming and verifying. * Lock bit programming and verifying. The Lock bit security is exactly as in parallel programming mode. If the Lock bits LB1 or LB2 are programmed, the OCDEN Fuse cannot be programmed unless first doing a chip erase. This is a security feature that ensures no back-door exists for reading out the content of a secured device. The details on programming through the JTAG interface and programming specific JTAG instructions are given in the section "Programming via the JTAG Interface" on page 211.
177
2548E-AVR-07/06
27. Boot Loader Support - Read-While-Write Self-Programming
The Boot Loader Support provides a real Read-While-Write Self-Programming mechanism for downloading and uploading program code by the MCU itself. This feature allows flexible application software updates controlled by the MCU using a Flash-resident Boot Loader program. The Boot Loader program can use any available data interface and associated protocol to read code and write (program) that code into the Flash memory, or read the code from the program memory. The program code within the Boot Loader section has the capability to write into the entire Flash, including the Boot Loader memory. The Boot Loader can thus even modify itself, and it can also erase itself from the code if the feature is not needed anymore. The size of the Boot Loader memory is configurable with fuses and the Boot Loader has two separate sets of Boot Lock bits which can be set independently. This gives the user a unique flexibility to select different levels of protection.
27.1
Boot Loader Features
* * * * * * *
Read-While-Write Self-Programming Flexible Boot Memory Size High Security (Separate Boot Lock Bits for a Flexible Protection) Separate Fuse to Select Reset Vector Optimized Page(1) Size Code Efficient Algorithm Efficient Read-Modify-Write Support 1. A page is a section in the Flash consisting of several bytes (see "Page Size" on page 198) used during programming. The page organization does not affect normal operation.
Note:
27.2
Application and Boot Loader Flash Sections
The Flash memory is organized in two main sections, the Application section and the Boot Loader section (see Figure 27-2). The size of the different sections is configured by the BOOTSZ Fuses as shown in Table 27-7 on page 193 and Figure 27-2. These two sections can have different level of protection since they have different sets of Lock bits.
27.2.1
Application Section The Application section is the section of the Flash that is used for storing the application code. The protection level for the Application section can be selected by the application Boot Lock bits (Boot Lock bits 0), see Table 27-2 on page 182. The Application section can never store any Boot Loader code since the SPM instruction is disabled when executed from the Application section. BLS - Boot Loader Section While the Application section is used for storing the application code, the The Boot Loader software must be located in the BLS since the SPM instruction can initiate a programming when executing from the BLS only. The SPM instruction can access the entire Flash, including the BLS itself. The protection level for the Boot Loader section can be selected by the Boot Loader Lock bits (Boot Lock bits 1), see Table 27-3 on page 182.
27.2.2
178
ATmega406
2548E-AVR-07/06
ATmega406
27.3 Read-While-Write and No Read-While-Write Flash Sections
Whether the CPU supports Read-While-Write or if the CPU is halted during a Boot Loader software update is dependent on which address that is being programmed. In addition to the two sections that are configurable by the BOOTSZ Fuses as described above, the Flash is also divided into two fixed sections, the Read-While-Write (RWW) section and the No Read-WhileWrite (NRWW) section. The limit between the RWW- and NRWW sections is given in Table 278 on page 193 and Figure 27-2 on page 181. The main difference between the two sections is: * When erasing or writing a page located inside the RWW section, the NRWW section can be read during the operation. * When erasing or writing a page located inside the NRWW section, the CPU is halted during the entire operation. Note that the user software can never read any code that is located inside the RWW section during a Boot Loader software operation. The syntax "Read-While-Write section" refers to which section that is being programmed (erased or written), not which section that actually is being read during a Boot Loader software update. 27.3.1 RWW - Read-While-Write Section If a Boot Loader software update is programming a page inside the RWW section, it is possible to read code from the Flash, but only code that is located in the NRWW section. During an ongoing programming, the software must ensure that the RWW section never is being read. If the user software is trying to read code that is located inside the RWW section (i.e., by a call/jmp/lpm or an interrupt) during programming, the software might end up in an unknown state. To avoid this, the interrupts should either be disabled or moved to the Boot Loader section. The Boot Loader section is always located in the NRWW section. The RWW Section Busy bit (RWWSB) in the Store Program Memory Control and Status Register (SPMCSR) will be read as logical one as long as the RWW section is blocked for reading. After a programming is completed, the RWWSB must be cleared by software before reading code located in the RWW section. See Section "27.5.1" on page 183. for details on how to clear RWWSB. NRWW - No Read-While-Write Section The code located in the NRWW section can be read when the Boot Loader software is updating a page in the RWW section. When the Boot Loader code updates the NRWW section, the CPU is halted during the entire Page Erase or Page Write operation. Table 27-1. Read-While-Write Features
Which Section Can be Read During Programming? NRWW Section None CPU Halted? No Yes Read-While-Write Supported? Yes No
27.3.2
Which Section does the Z-pointer Address During the Programming? RWW Section NRWW Section
179
2548E-AVR-07/06
Figure 27-1. Read-While-Write vs. No Read-While-Write
Read-While-Write (RWW) Section
Z-pointer Addresses RWW Section
Z-pointer Addresses NRWW Section
No Read-While-Write (NRWW) Section
CPU is Halted During the Operation Code Located in NRWW Section Can be Read During the Operation
180
ATmega406
2548E-AVR-07/06
ATmega406
Figure 27-2. Memory Sections
Program Memory BOOTSZ = '11' 0x0000
Read-While-Write Section Read-While-Write Section
Program Memory BOOTSZ = '10' 0x0000
Application Flash Section
Application Flash Section
No Read-While-Write Section
End RWW Start NRWW Application Flash Section
No Read-While-Write Section
End RWW Start NRWW Application Flash Section End Application Start Boot Loader Boot Loader Flash Section Flashend Program Memory BOOTSZ = '00'
Boot Loader Flash Section
End Application Start Boot Loader Flashend
Program Memory BOOTSZ = '01' 0x0000
Read-While-Write Section Read-While-Write Section
0x0000
Application Flash Section
Application Flash Section
No Read-While-Write Section
End RWW Start NRWW Application Flash Section End Application Start Boot Loader Boot Loader Flash Section Flashend
No Read-While-Write Section
End RWW, End Application Start NRWW, Start Boot Loader
Boot Loader Flash Section
Flashend
Note:
1. The parameters in the figure above are given in Table 27-7 on page 193.
27.4
Boot Loader Lock Bits
If no Boot Loader capability is needed, the entire Flash is available for application code. The Boot Loader has two separate sets of Boot Lock bits which can be set independently. This gives the user a unique flexibility to select different levels of protection. The user can select: * To protect the entire Flash from a software update by the MCU. * To protect only the Boot Loader Flash section from a software update by the MCU. * To protect only the Application Flash section from a software update by the MCU. * Allow software update in the entire Flash. See Table 27-2 and Table 27-3 for further details. The Boot Lock bits can be set in software and in Serial or Parallel Programming mode, but they can be cleared by a Chip Erase command only. The general Write Lock (Lock Bit mode 2) does not control the programming of the Flash memory by SPM instruction. Similarly, the general Read/Write Lock (Lock Bit mode 1) does not control reading nor writing by LPM/SPM, if it is attempted. 181
2548E-AVR-07/06
Table 27-2.
BLB0 Mode 1 2
Boot Lock Bit0 Protection Modes (Application Section)(1)
BLB02 1 1 BLB01 1 0 Protection No restrictions for SPM or LPM accessing the Application section. SPM is not allowed to write to the Application section. SPM is not allowed to write to the Application section, and LPM executing from the Boot Loader section is not allowed to read from the Application section. If Interrupt Vectors are placed in the Boot Loader section, interrupts are disabled while executing from the Application section. LPM executing from the Boot Loader section is not allowed to read from the Application section. If Interrupt Vectors are placed in the Boot Loader section, interrupts are disabled while executing from the Application section.
3
0
0
4
0
1
Note:
1. "1" means unprogrammed, "0" means programmed
Table 27-3.
BLB1 Mode 1 2
Boot Lock Bit1 Protection Modes (Boot Loader Section)(1)
BLB12 1 1 BLB11 1 0 Protection No restrictions for SPM or LPM accessing the Boot Loader section. SPM is not allowed to write to the Boot Loader section. SPM is not allowed to write to the Boot Loader section, and LPM executing from the Application section is not allowed to read from the Boot Loader section. If Interrupt Vectors are placed in the Application section, interrupts are disabled while executing from the Boot Loader section. LPM executing from the Application section is not allowed to read from the Boot Loader section. If Interrupt Vectors are placed in the Application section, interrupts are disabled while executing from the Boot Loader section.
3
0
0
4
0
1
Note:
1. "1" means unprogrammed, "0" means programmed
182
ATmega406
2548E-AVR-07/06
ATmega406
27.5 Entering the Boot Loader Program
Entering the Boot Loader takes place by a jump or call from the application program. This may be initiated by a trigger such as a command received via the TWI interface. Alternatively, the Boot Reset Fuse can be programmed so that the Reset Vector is pointing to the Boot Flash start address after a reset. In this case, the Boot Loader is started after a reset. After the application code is loaded, the program can start executing the application code. Note that the fuses cannot be changed by the MCU itself. This means that once the Boot Reset Fuse is programmed, the Reset Vector will always point to the Boot Loader Reset and the fuse can only be changed through the serial or parallel programming interface. Table 27-4.
BOOTRST 1 0 Note:
Boot Reset Fuse(1)
Reset Address Reset Vector = Application Reset (address 0x0000) Reset Vector = Boot Loader Reset (see Table 27-7 on page 193)
1. "1" means unprogrammed, "0" means programmed
27.5.1
SPMCSR - Store Program Memory Control and Status Register The Store Program Memory Control and Status Register contains the control bits needed to control the Boot Loader operations.
Bit 0x37 (0x57) Read/Write Initial Value 7
SPMIE
6
RWWSB
5
SIGRD
4
RWWSRE
3
BLBSET
2
PGWRT
1
PGERS
0
SPMEN SPMCSR
R/W 0
R 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
* Bit 7 - SPMIE: SPM Interrupt Enable When the SPMIE bit is written to one, and the I-bit in the Status Register is set (one), the SPM ready interrupt will be enabled. The SPM ready Interrupt will be executed as long as the SPMEN bit in the SPMCSR Register is cleared. * Bit 6 - RWWSB: Read-While-Write Section Busy When a Self-Programming (Page Erase or Page Write) operation to the RWW section is initiated, the RWWSB will be set (one) by hardware. When the RWWSB bit is set, the RWW section cannot be accessed. The RWWSB bit will be cleared if the RWWSRE bit is written to one after a Self-Programming operation is completed. Alternatively the RWWSB bit will automatically be cleared if a page load operation is initiated. * Bit 5 - SIGRD: Signature Row Read If this bit is written to one at the same time as SPMEN, the next LPM instruction within three clock cycles will read a byte from the signature row into the destination register. see "Reading the Signature Row from Software" on page 189 for details. An SPM instruction within four cycles after SIGRD and SPMEN are set will have no effect. This operation is reserved for future use and should not be used.
183
2548E-AVR-07/06
* Bit 4 - RWWSRE: Read-While-Write Section Read Enable When programming (Page Erase or Page Write) to the RWW section, the RWW section is blocked for reading (the RWWSB will be set by hardware). To re-enable the RWW section, the user software must wait until the programming is completed (SPMEN will be cleared). Then, if the RWWSRE bit is written to one at the same time as SPMEN, the next SPM instruction within four clock cycles re-enables the RWW section. The RWW section cannot be re-enabled while the Flash is busy with a Page Erase or a Page Write (SPMEN is set). If the RWWSRE bit is written while the Flash is being loaded, the Flash load operation will abort and the data loaded will be lost. * Bit 3 - BLBSET: Boot Lock Bit Set If this bit is written to one at the same time as SPMEN, the next SPM instruction within four clock cycles sets Boot Lock bits, according to the data in R0. The data in R1 and the address in the Zpointer are ignored. The BLBSET bit will automatically be cleared upon completion of the Lock bit set, or if no SPM instruction is executed within four clock cycles. An LPM instruction within three cycles after BLBSET and SPMEN are set in the SPMCSR Register, will read either the Lock bits or the Fuse bits (depending on Z0 in the Z-pointer) into the destination register. See "Reading the Fuse and Lock Bits from Software" on page 188 for details. * Bit 2 - PGWRT: Page Write If this bit is written to one at the same time as SPMEN, the next SPM instruction within four clock cycles executes Page Write, with the data stored in the temporary buffer. The page address is taken from the high part of the Z-pointer. The data in R1 and R0 are ignored. The PGWRT bit will auto-clear upon completion of a Page Write, or if no SPM instruction is executed within four clock cycles. The CPU is halted during the entire Page Write operation if the NRWW section is addressed. * Bit 1 - PGERS: Page Erase If this bit is written to one at the same time as SPMEN, the next SPM instruction within four clock cycles executes Page Erase. The page address is taken from the high part of the Z-pointer. The data in R1 and R0 are ignored. The PGERS bit will auto-clear upon completion of a Page Erase, or if no SPM instruction is executed within four clock cycles. The CPU is halted during the entire Page Write operation if the NRWW section is addressed. * Bit 0 - SPMEN: Store Program Memory Enable This bit enables the SPM instruction for the next four clock cycles. If written to one together with either RWWSRE, BLBSET, PGWRT' or PGERS, the following SPM instruction will have a special meaning, see description above. If only SPMEN is written, the following SPM instruction will store the value in R1:R0 in the temporary page buffer addressed by the Z-pointer. The LSB of the Z-pointer is ignored. The SPMEN bit will auto-clear upon completion of an SPM instruction, or if no SPM instruction is executed within four clock cycles. During Page Erase and Page Write, the SPMEN bit remains high until the operation is completed. Writing any other combination than "100001", "010001", "001001", "000101", "000011" or "000001" in the lower five bits will have no effect.
184
ATmega406
2548E-AVR-07/06
ATmega406
27.6 Addressing the Flash During Self-Programming
The Z-pointer is used to address the SPM commands.
Bit ZH (R31) ZL (R30) 15 Z15 Z7 7 14 Z14 Z6 6 13 Z13 Z5 5 12 Z12 Z4 4 11 Z11 Z3 3 10 Z10 Z2 2 9 Z9 Z1 1 8 Z8 Z0 0
Since the Flash is organized in pages (see "Fuse Bits" on page 196), the Program Counter can be treated as having two different sections. One section, consisting of the least significant bits, is addressing the words within a page, while the most significant bits are addressing the pages. This is shown in Figure 27-3. Note that the Page Erase and Page Write operations are addressed independently. Therefore it is of major importance that the Boot Loader software addresses the same page in both the Page Erase and Page Write operation. Once a programming operation is initiated, the address is latched and the Z-pointer can be used for other operations. The only SPM operation that does not use the Z-pointer is Setting the Boot Loader Lock bits. The content of the Z-pointer is ignored and will have no effect on the operation. The LPM instruction does also use the Z-pointer to store the address. Since this instruction addresses the Flash byte-by-byte, also the LSB (bit Z0) of the Z-pointer is used. Figure 27-3. Addressing the Flash During SPM(1)
BIT Z - REGISTER PCMSB PROGRAM COUNTER
PCPAGE
15
ZPCMSB
ZPAGEMSB
10 0
PAGEMSB
PCWORD
PAGE ADDRESS WITHIN THE FLASH PROGRAM MEMORY
PAGE
WORD ADDRESS WITHIN A PAGE
PAGE INSTRUCTION WORD PCWORD[PAGEMSB:0]: 00 01 02
PAGEEND
Note:
1. The different variables used in Figure 27-3 are listed in Table 27-9 on page 193.
185
2548E-AVR-07/06
27.7
Self-Programming the Flash
The program memory is updated in a page by page fashion. Before programming a page with the data stored in the temporary page buffer, the page must be erased. The temporary page buffer is filled one word at a time using SPM and the buffer can be filled either before the Page Erase command or between a Page Erase and a Page Write operation: Alternative 1, fill the buffer before a Page Erase * Fill temporary page buffer * Perform a Page Erase * Perform a Page Write Alternative 2, fill the buffer after Page Erase * Perform a Page Erase * Fill temporary page buffer * Perform a Page Write If only a part of the page needs to be changed, the rest of the page must be stored (for example in the temporary page buffer) before the erase, and then be rewritten. When using alternative 1, the Boot Loader provides an effective Read-Modify-Write feature which allows the user software to first read the page, do the necessary changes, and then write back the modified data. If alternative 2 is used, it is not possible to read the old data while loading since the page is already erased. The temporary page buffer can be accessed in a random sequence. It is essential that the page address used in both the Page Erase and Page Write operation is addressing the same page. See "Simple Assembly Code Example for a Boot Loader" on page 191 for an assembly code example.
27.7.1
Performing Page Erase by SPM To execute Page Erase, set up the address in the Z-pointer, write "X0000011" to SPMCSR and execute SPM within four clock cycles after writing SPMCSR. The data in R1 and R0 is ignored. The page address must be written to PCPAGE in the Z-register. Other bits in the Z-pointer will be ignored during this operation. * Page Erase to the RWW section: The NRWW section can be read during the Page Erase. * Page Erase to the NRWW section: The CPU is halted during the operation.
27.7.2
Filling the Temporary Buffer (Page Loading) To write an instruction word, set up the address in the Z-pointer and data in R1:R0, write "00000001" to SPMCSR and execute SPM within four clock cycles after writing SPMCSR. The content of PCWORD in the Z-register is used to address the data in the temporary buffer. The temporary buffer will auto-erase after a Page Write operation or by writing the RWWSRE bit in SPMCSR. It is also erased after a system reset. Note that it is not possible to write more than one time to each address without erasing the temporary buffer.
186
ATmega406
2548E-AVR-07/06
ATmega406
27.7.3 Performing a Page Write To execute Page Write, set up the address in the Z-pointer, write "X0000101" to SPMCSR and execute SPM within four clock cycles after writing SPMCSR. The data in R1 and R0 is ignored. The page address must be written to PCPAGE. Other bits in the Z-pointer will be ignored during this operation. * Page Write to the RWW section: The NRWW section can be read during the Page Write. * Page Write to the NRWW section: The CPU is halted during the operation. 27.7.4 Using the SPM Interrupt If the SPM interrupt is enabled, the SPM interrupt will generate a constant interrupt when the SPMEN bit in SPMCSR is cleared. This means that the interrupt can be used instead of polling the SPMCSR Register in software. When using the SPM interrupt, the Interrupt Vectors should be moved to the BLS section to avoid that an interrupt is accessing the RWW section when it is blocked for reading. How to move the interrupts is described in "Interrupts" on page 51. Consideration While Updating BLS Special care must be taken if the user allows the Boot Loader section to be updated by leaving Boot Lock bit11 unprogrammed. An accidental write to the Boot Loader itself can corrupt the entire Boot Loader, and further software updates might be impossible. If it is not necessary to change the Boot Loader software itself, it is recommended to program the Boot Lock bit11 to protect the Boot Loader software from any internal software changes. Prevent Reading the RWW Section During Self-Programming During Self-Programming (either Page Erase or Page Write), the RWW section is always blocked for reading. The user software itself must prevent that this section is addressed during the self programming operation. The RWWSB in the SPMCSR will be set as long as the RWW section is busy. During Self-Programming the Interrupt Vector table should be moved to the BLS as described in "Interrupts" on page 51, or the interrupts must be disabled. Before addressing the RWW section after the programming is completed, the user software must clear the RWWSB by writing the RWWSRE. See "Simple Assembly Code Example for a Boot Loader" on page 191 for an example. Setting the Boot Loader Lock Bits by SPM To set the Boot Loader Lock bits, write the desired data to R0, write "X0001001" to SPMCSR and execute SPM within four clock cycles after writing SPMCSR. The only accessible Lock bits are the Boot Lock bits that may prevent the Application and Boot Loader section from any software update by the MCU.
Bit R0 7 1 6 1 5 BLB12 4 BLB11 3 BLB02 2 BLB01 1 1 0 1
27.7.5
27.7.6
27.7.7
See Table 27-2 and Table 27-3 for how the different settings of the Boot Loader bits affect the Flash access. If bits 5:2 in R0 are cleared (zero), the corresponding Boot Lock bit will be programmed if an SPM instruction is executed within four cycles after BLBSET and SPMEN are set in SPMCSR. The Z-pointer is don't care during this operation, but for future compatibility it is recommended to load the Z-pointer with 0x0001 (same as used for reading the lOck bits). For future compatibility it
187
2548E-AVR-07/06
is also recommended to set bits 7, 6, 1, and 0 in R0 to "1" when writing the Lock bits. When programming the Lock bits the entire Flash can be read during the operation. 27.7.8 EEPROM Write Prevents Writing to SPMCSR Note that an EEPROM write operation will block all software programming to Flash. Reading the Fuses and Lock bits from software will also be prevented during the EEPROM write operation. It is recommended that the user checks the status bit (EEWE) in the EECR Register and verifies that the bit is cleared before writing to the SPMCSR Register. Reading the Fuse and Lock Bits from Software It is possible to read both the Fuse and Lock bits from software. To read the Lock bits, load the Z-pointer with 0x0001 and set the BLBSET and SPMEN bits in SPMCSR. When an LPM instruction is executed within three CPU cycles after the BLBSET and SPMEN bits are set in SPMCSR, the value of the Lock bits will be loaded in the destination register. The BLBSET and SPMEN bits will auto-clear upon completion of reading the Lock bits or if no LPM instruction is executed within three CPU cycles or no SPM instruction is executed within four CPU cycles. When BLBSET and SPMEN are cleared, LPM will work as described in the "AVR Instruction Set" description.
Bit Rd 7 - 6 - 5 BLB12 4 BLB11 3 BLB02 2 BLB01 1 LB2 0 LB1
27.7.9
The algorithm for reading the Fuse Low byte is similar to the one described above for reading the Lock bits. To read the Fuse Low byte, load the Z-pointer with 0x0000 and set the BLBSET and SPMEN bits in SPMCSR. When an LPM instruction is executed within three cycles after the BLBSET and SPMEN bits are set in the SPMCSR, the value of the Fuse Low byte (FLB) will be loaded in the destination register as shown below. Refer to Table 28-4 on page 197 for a detailed description and mapping of the Fuse Low byte.
Bit Rd 7 FLB7 6 FLB6 5 FLB5 4 FLB4 3 FLB3 2 FLB2 1 FLB1 0 FLB0
Similarly, when reading the Fuse High byte, load 0x0003 in the Z-pointer. When an LPM instruction is executed within three cycles after the BLBSET and SPMEN bits are set in the SPMCSR, the value of the Fuse High byte (FHB) will be loaded in the destination register as shown below. Refer to Table 28-3 on page 196 for detailed description and mapping of the Fuse High byte.
Bit Rd 7 FHB7 6 FHB6 5 FHB5 4 FHB4 3 FHB3 2 FHB2 1 FHB1 0 FHB0
Fuse and Lock bits that are programmed, will be read as zero. Fuse and Lock bits that are unprogrammed, will be read as one.
188
ATmega406
2548E-AVR-07/06
ATmega406
27.7.10 Reading the Signature Row from Software To read the Signature Row from software, load the Z-pointer with the signature byte address given in Table 27-5 and set the SIGRD and SPMEN bits in SPMCSR. When an LPM instruction is executed within three CPU cycles after the SIGRD and SPMEN bits are set in SPMCSR, the signature byte value will be loaded in the destination register. The SIGRD and SPMEN bits will auto-clear upon completion of reading the Signature Row Lock bits or if no LPM instruction is executed within three CPU cycles. When SIGRD and SPMEN are cleared, LPM will work as described in the "AVR Instruction Set" description.
Table 27-5.
Signature Row Addressing
Z-Pointer Address 0x00 0x02 0x04 0x01 0x03
(2)
Signature Byte Device ID 0, Manufacture ID Device ID 1, Flash Size Device ID 2, Device FOSCCAL(1) Reserved Slow RC FRQ Slow RC L Slow RC H
(3)
0x05 0x06 0x07 0x0C
(7)
Slow RC Temp Prediction L Slow RC Temp Prediction H ULP RC FRQ(5) ULP RC L ULP RC H
(6) (4)
0x0D 0x08 0x0A 0x0B 0x09 0x0E 0x0F 0x10
(9)
Bandgap PTAT Current Calibration Byte V-ADC RAW Cell 1 L V-ADC RAW Cell 1 H(8) V-ADC Cell1 Gain Calibration Word L V-ADC Cell1 Gain Calibration Word H V-ADC Cell2 Gain Calibration Word L V-ADC Cell2 Gain Calibration Word H V-ADC Cell3 Gain Calibration Word L V-ADC Cell3 Gain Calibration Word H V-ADC Cell4 Gain Calibration Word L V-ADC Cell4 Gain Calibration Word H
(9) (9) (9)
0x11 0x12 0x13 0x14 0x15 0x16 0x17 0x18
V-ADC ADC0 Gain Calibration Word L V-ADC ADC0 Gain Calibration Word H V-ADC Cell1 Offset(12)
(10)
0x19 0x1C
189
2548E-AVR-07/06
Table 27-5.
Signature Row Addressing
Z-Pointer Address
(12) (12)
Signature Byte V-ADC Cell2 Offse V-ADC Cell3 Offse t t
0x1D 0x1E 0x1F 0x1A 0x1B
V-ADC Cell4 Offset VPTAT CAL L VPTAT CAL H(11) Notes: 1. 2. 3. 4. 5. 6. 7.
(12)
Default FOSCCAL value after reset. Slow RC oscillator Frequency in kHz Slow RC Oscillator fastest timeout in s. Calibration value found for BGCCR which gives 1.1V at VREF when BGCRR = 0x0F. ULP RC Oscillator Frequency in kHz. ULP RC Oscillator fastest timeout in s. Slow RC Oscillator Frequency Temperature drift prediction value (word). Measured over several lots. Not implemented. 8. Calibration Word used for the second step of VREF calibration. This step is performed by the customer at 25C. Value stored is VADCH/L when Cell1 had 4096 mV at 85C. 9. Calibration Word used to compensate for gain error in V-ADC Cell input 1 - 4. Cell x in mV = VADCH/L*this word/16384. 10. Calibration Word used to compensate for gain error in V-ADC ADC0. ADC0 in mV = VADCH/L*this word/16384. 11. Calibration Word used to calculate the absolute temperature in Kelvin from VTEMP conversion. Temp in K = VADCH/L*this word/16384. 12. Calibration Byte used to compensate for offset in V-ADC Cells. Not implemented.
All other addresses are reserved for future use.
190
ATmega406
2548E-AVR-07/06
ATmega406
27.7.11 Programming Time for Flash when Using SPM The Fast RC Oscillator is used to time Flash accesses. Table 27-6 shows the typical programming time for Flash accesses from the CPU. Table 27-6. SPM Programming Time
Symbol Flash write (Page Erase, Page Write, and write Lock bits by SPM) Min Programming Time 3.7 ms Max Programming Time 4.5 ms
27.7.12
Simple Assembly Code Example for a Boot Loader
;-the routine writes one page of data from RAM to Flash ; the first data location in RAM is pointed to by the Y pointer ; the first data location in Flash is pointed to by the Z-pointer ;-error handling is not included ;-the routine must be placed inside the Boot space ; (at least the Do_spm sub routine). Only code inside NRWW section ; can be read during Self-Programming (Page Erase and Page Write). ;-registers used: r0, r1, temp1 (r16), temp2 (r17), looplo (r24), ; loophi (r25), spmcrval (r20) ; storing and restoring of registers is not included in the routine ; register usage can be optimized at the expense of code size ;-It is assumed that either the interrupt table is moved to the ; Boot loader section or that the interrupts are disabled. .equ PAGESIZEB = PAGESIZE*2 ;PAGESIZEB is page size in BYTES, not words .org SMALLBOOTSTART Write_page: ; Page Erase ldi spmcrval, (1<191
2548E-AVR-07/06
ldi spmcrval, (1<192
ATmega406
2548E-AVR-07/06
ATmega406
27.7.13 ATmega406 Boot Loader Parameters In Table 27-7 through Table 27-9, the parameters used in the description of the Self-Programming are given Table 27-7. Boot Size Configuration(1)
End Application Section Boot Reset Address (Start Boot Loader Section) 0x4F00 0x4E00 0x4C00 0x4800 Application Flash Section Boot Loader Flash Section 0x4F00 0x4FFF 0x4E00 0x4FFF 0x4C00 0x4FFF 0x4800 0x4FFF
BOOTSZ1
BOOTSZ0
Boot Size
1 1 0 0 Note:
1 0 1 0
256 words 512 words 1024 words 2048 words
Pages
4 8 16 32
0x0000 0x4EFF 0x0000 0x4DFF 0x0000 0x4BFF 0x0000 0x47FF
0x4EFF 0x4DFF 0x4BFF 0x47FF
1. The different BOOTSZ Fuse configurations are shown in Figure 27-2
Table 27-8.
Section
Read-While-Write Limit(1)
Pages 288 32 Address 0x0000 - 0x47FF 0x4800 - 0x4FFF
Read-While-Write section (RWW) No Read-While-Write section (NRWW) Note:
1. For details about these two section, see "NRWW - No Read-While-Write Section" on page 179 and "RWW - Read-While-Write Section" on page 179.
Table 27-9.
Explanation of different variables used in Figure 27-3 and the mapping to the Zpointer(1)
Corresponding Z-value 14 Description Most significant bit in the Program Counter. (The Program Counter is 13 bits PC[12:0]) Most significant bit which is used to address the words within one page (64 words in a page requires six bits PC [5:0]). Z15 Bit in Z-register that is mapped to PCMSB. Because Z0 is not used, the ZPCMSB equals PCMSB + 1. Bit in Z-register that is mapped to PCMSB. Because Z0 is not used, the ZPAGEMSB equals PAGEMSB + 1. Program Counter page address: Page select, for Page Erase and Page Write Program Counter word address: Word select, for filling temporary buffer (must be zero during Page Write operation)
Variable PCMSB
PAGEMSB
5
ZPCMSB
ZPAGEMSB
Z6
PCPAGE
PC[14:6]
Z13:Z7
PCWORD
PC[5:0]
Z6:Z1
193
2548E-AVR-07/06
Note:
1. Z0: should be zero for all SPM commands, byte select for the LPM instruction. See "Addressing the Flash During Self-Programming" on page 185 for details about the use of Z-pointer during Self-Programming.
194
ATmega406
2548E-AVR-07/06
ATmega406
28. Memory Programming
28.1 Program And Data Memory Lock Bits
The ATmega406 provides six Lock bits which can be left unprogrammed ("1") or can be programmed ("0") to obtain the additional features listed in Table 28-2. The Lock bits can only be erased to "1" with the Chip Erase command. Table 28-1.
Lock Bit Byte
Lock Bit Byte(1)
Bit No 7 6 Description - - Boot Lock bit Boot Lock bit Boot Lock bit Boot Lock bit Lock bit Lock bit Default Value 1 (unprogrammed) 1 (unprogrammed) 1 (unprogrammed) 1 (unprogrammed) 1 (unprogrammed) 1 (unprogrammed) 1 (unprogrammed) 1 (unprogrammed)
BLB12 BLB11 BLB02 BLB01 LB2 LB1 Note:
5 4 3 2 1 0
1. "1" means unprogrammed, "0" means programmed
Table 28-2.
Lock Bit Protection Modes(1)(2)
Protection Type LB1 1 0 No memory lock features enabled. Further programming of the Flash and EEPROM is disabled in Parallel and Serial Programming mode. The Fuse bits are locked in both Serial and Parallel Programming mode.(1) Further programming and verification of the Flash and EEPROM is disabled in Parallel and Serial Programming mode. The Boot Lock bits and Fuse bits are locked in both Serial and Parallel Programming mode.(1)
Memory Lock Bits LB Mode 1 2 LB2 1 1
3
0
0
BLB0 Mode 1 2
BLB02 1 1
BLB01 1 0 No restrictions for SPM or LPM accessing the Application section. SPM is not allowed to write to the Application section. SPM is not allowed to write to the Application section, and LPM executing from the Boot Loader section is not allowed to read from the Application section. If Interrupt Vectors are placed in the Boot Loader section, interrupts are disabled while executing from the Application section. LPM executing from the Boot Loader section is not allowed to read from the Application section. If Interrupt Vectors are placed in the Boot Loader section, interrupts are disabled while executing from the Application section.
3
0
0
4
0
1
195
2548E-AVR-07/06
Table 28-2.
Lock Bit Protection Modes(1)(2) (Continued)
Protection Type
Memory Lock Bits BLB1 Mode 1 2 BLB12 1 1 BLB11 1 0
No restrictions for SPM or LPM accessing the Boot Loader section. SPM is not allowed to write to the Boot Loader section. SPM is not allowed to write to the Boot Loader section, and LPM executing from the Application section is not allowed to read from the Boot Loader section. If Interrupt Vectors are placed in the Application section, interrupts are disabled while executing from the Boot Loader section. LPM executing from the Application section is not allowed to read from the Boot Loader section. If Interrupt Vectors are placed in the Application section, interrupts are disabled while executing from the Boot Loader section.
3
0
0
4
0
1
Notes:
1. Program the Fuse bits and Boot Lock bits before programming the LB1 and LB2. 2. "1" means unprogrammed, "0" means programmed
28.2
Fuse Bits
The ATmega406 has two Fuse bytes. Table 28-3 - Table 28-4 describe briefly the functionality of all the fuses and how they are mapped into the Fuse bytes. Note that the fuses are read as logical zero, "0", if they are programmed.
28.2.1
High Byte
Table 28-3.
Fuse High Byte
Bit No 7 6 5 4 3 2 1 0 Description - - - - - - Enable OCD Enable JTAG Default Value 1 1 1 1 1 1 1 (unprogrammed, OCD disabled) 0 (programmed, JTAG enabled)
Fuse High Byte - - - - - - OCDEN(1) JTAGEN Notes:
1. Never ship a product with the OCDEN Fuse programmed regardless of the setting of Lock bits and JTAGEN Fuse. A programmed OCDEN Fuse enables some parts of the clock system to be running in all sleep modes. This may increase the power consumption.
196
ATmega406
2548E-AVR-07/06
ATmega406
28.2.2 Low Byte Table 28-4.
(3)
Fuse Low Byte
Bit No 7 6 5 4 3 2 1 0 Description Watchdog Timer always on EEPROM memory is preserved through the Chip Erase Select Boot Size (see Table 27-7 on page 193 for details) Select Boot Size (see Table 27-7 on page 193 for details) Select Reset Vector Select start-up time Select start-up time Clock Selection Default Value 1 (unprogrammed) 1 (unprogrammed, EEPROM not preserved) 0 (programmed)(2) 0 (programmed)(2) 1 (unprogrammed) 1 (unprogrammed)(1) 0 (programmed)(1) 1 (unprogrammed)(4)
Fuse Low Byte WDTON
EESAVE BOOTSZ1 BOOTSZ0 BOOTRST SUT1 SUT0 CKSEL Notes:
1. The default value of SUT1:0 results in maximum start-up time for the default clock source. See Table 7-2 on page 28 for details. 2. The default value of BOOTSZ1:0 results in maximum Boot Size. See Table 27-7 on page 193 for details. 3. See "WDTCSR - Watchdog Timer Control Register" on page 47 for details. 4. When unpgrogrammed, Internal RC Oscillator is used. Programming this fuse is for test purpose only, and should not be used in application.
The status of the Fuse bits is not affected by Chip Erase. Note that the Fuse bits are locked if Lock bit1 (LB1) is programmed. Program the Fuse bits before programming the Lock bits. 28.2.3 Latching of Fuses The fuse values are latched when the device enters programming mode and changes of the fuse values will have no effect until the part leaves Programming mode. This does not apply to the EESAVE Fuse which will take effect once it is programmed. The fuses are also latched on Power-up in Normal mode.
197
2548E-AVR-07/06
28.3
Signature Bytes
All Atmel microcontrollers have a three-byte signature code which identifies the device. This code can be read in both serial and parallel mode, also when the device is locked. The three bytes reside in a separate address space. For the ATmega406 the signature bytes are: 1. 0x000: 0x1E (indicates manufactured by Atmel). 2. 0x001: 0x95 (indicates 40KB Flash memory). 3. 0x002: 0x07(indicates ATmega406 device when 0x001 is 0x95).
28.4
Calibration Bytes
The ATmega406 has calibration bytes for the Fast RC Oscillator, Slow RC Oscillator, internal voltage reference, internal temperature reference and each differential cell voltage input. These bytes reside in the high bytes in the signature address space. During Reset, the calibration byte for the Fast RC Oscillator is automatically written into the corresponding calibration register. The other calibration bytes should be handled by the application software. See "Reading the Signature Row from Software" on page 189 for details.
28.5
Page Size
Table 28-5. No. of Words in a Page and No. of Pages in the Flash
Page Size 64 words PCWORD PC[5:0] No. of Pages 320 PCPAGE PC[14:6] PCMSB 14
Flash Size 20K words (40K bytes)
Table 28-6.
No. of Words in a Page and No. of Pages in the EEPROM
Page Size 4 bytes PCWORD EEA[1:0] No. of Pages 128 PCPAGE EEA[8:2] EEAMSB 8
EEPROM Size 512 bytes
198
ATmega406
2548E-AVR-07/06
ATmega406
28.6 Parallel Programming
This section describes parameters, pin mapping, and commands used to parallel program and verify Flash Program memory, EEPROM Data memory, Memory Lock bits, and Fuse bits in the ATmega406. Pulses are assumed to be at least 250 ns unless otherwise noted. 28.6.1 Considerations for Efficient Programming The loaded command and address are retained in the device during programming. For efficient programming, the following should be considered. * The command needs only be loaded once when writing or reading multiple memory locations. * Skip writing the data value 0xFF, that is the contents of the entire EEPROM (unless the EESAVE Fuse is programmed) and Flash after a Chip Erase. Address high byte needs only be loaded before programming or reading a new 256 word window in Flash or 256 byte EEPROM. This consideration also applies to Signature bytes reading. 28.6.2 Signal Names In this section, some pins of the ATmega406 are referenced by signal names describing their functionality during parallel programming, see Figure 28-1 on page 199 and Table 28-7 on page 200. Pins not described in the following table are referenced by pin names. The XA1/XA0 pins determine the action executed when the XTAL1 pin is given a positive pulse. The bit coding is shown in Table 28-9 on page 200. When pulsing WR or OE, the command loaded determines the action executed. The different Commands are shown in Table 28-10 on page 201. Table 28-11 on page 210 shows the Parallel programming characteristics. Figure 28-1. Parallel Programming
+4 - 25V
RDY/BSY OE WR BS1 XA0 XA1 PAGEL VPP BS2 XTAL1 GND RESET
VFET VREG
VCC
(3.3V)
BATT PVT PV1
See "Enter Programming Mode"
DATA
199
2548E-AVR-07/06
Table 28-7.
Pin Name Mapping
Pin Name PA0 PA1 PA2 PA3 PA4 PA5 PA6 PA7 PB7:0 I/O I O I I I I I I I/O Function Byte Select 2 ("0" selects low byte, "1" selects 2'nd high byte). 0: Device is busy programming, 1: Device is ready for new command. Output Enable (Active low). Write Pulse (Active low). Byte Select 1 ("0" selects low byte, "1" selects high byte). XTAL Action Bit 0 XTAL Action Bit 1 Program Memory and EEPROM data Page Load. Bi-directional Data bus (Output when OE is low).
Signal Name in Programming Mode BS2 RDY/BSY OE WR BS1 XA0 XA1 PAGEL DATA
Table 28-8.
Pin
Pin Values Used to Enter Programming Mode
Symbol Prog_enable[3] Prog_enable[2] Prog_enable[1] Prog_enable[0] Value 0 0 0 0
PAGEL XA1 XA0 BS1
Table 28-9.
XA1 0 0 1 1
XA1 and XA0 Coding
XA0 0 1 0 1 Action when XTAL1 is Pulsed Load Flash or EEPROM Address (High or low address byte determined by BS1). Load Data (High or Low data byte for Flash determined by BS1). Load Command No Action, Idle
200
ATmega406
2548E-AVR-07/06
ATmega406
Table 28-10. Command Byte Bit Coding
Command Byte 1000 0000 0100 0000 0010 0000 0001 0000 0001 0001 0000 1000 0000 0100 0000 0010 0000 0011 Command Executed Chip Erase Write Fuse bits Write Lock bits Write Flash Write EEPROM Read Signature Bytes and Calibration byte Read Fuse and Lock bits Read Flash Read EEPROM
28.6.3
Enter Programming Mode The following algorithm puts the device in parallel programming mode: 1. Make sure the chip is started as explained in Section 9.2.1 "Power-on Reset and Charger Connect" on page 40. 2. Set RESET to "0" and toggle XTAL1 at least six times. 3. Set the Prog_enable pins listed in Table 28-8 on page 200 to "0000" and wait at least 100 ns. 4. Apply 11.5 - 12.5V to RESET. Any activity on Prog_enable pins within 100 ns after +12V has been applied to RESET, will cause the device to fail entering programming mode. 5. Wait at least 50 s before sending a new command.
28.6.4
Chip Erase The Chip Erase will erase the Flash and EEPROM(1) memories plus Lock bits. The Lock bits are not reset until the program memory has been completely erased. The Fuse bits are not changed. A Chip Erase must be performed before the Flash and/or EEPROM are reprogrammed.
Note: 1. The EEPRPOM memory is preserved during Chip Erase if the EESAVE Fuse is programmed.
Load Command "Chip Erase" 1. Set XA1, XA0 to "10". This enables command loading. 2. Set BS1 to "0". 3. Set DATA to "1000 0000". This is the command for Chip Erase. 4. Give XTAL1 a positive pulse. This loads the command. 5. Give WR a negative pulse. This starts the Chip Erase. RDY/BSY goes low. 6. Wait until RDY/BSY goes high before loading a new command.
201
2548E-AVR-07/06
28.6.5
Programming the Flash The Flash is organized in pages, see Table 28-5 on page 198. When programming the Flash, the program data is latched into a page buffer. This allows one page of program data to be programmed simultaneously. The following procedure describes how to program the entire Flash memory: A. Load Command "Write Flash" 1. Set XA1, XA0 to "10". This enables command loading. 2. Set BS1 to "0". 3. Set DATA to "0001 0000". This is the command for Write Flash. 4. Give XTAL1 a positive pulse. This loads the command. B. Load Address Low byte 1. Set XA1, XA0 to "00". This enables address loading. 2. Set BS1 to "0". This selects low address. 3. Set DATA = Address low byte (0x00 - 0xFF). 4. Give XTAL1 a positive pulse. This loads the address low byte. C. Load Data Low Byte 1. Set XA1, XA0 to "01". This enables data loading. 2. Set DATA = Data low byte (0x00 - 0xFF). 3. Give XTAL1 a positive pulse. This loads the data byte. D. Load Data High Byte 1. Set BS1 to "1". This selects high data byte. 2. Set XA1, XA0 to "01". This enables data loading. 3. Set DATA = Data high byte (0x00 - 0xFF). 4. Give XTAL1 a positive pulse. This loads the data byte. E. Latch Data 1. Set BS1 to "1". This selects high data byte. 2. Give PAGEL a positive pulse. This latches the data bytes. (See Figure 28-3 for signal waveforms) F. Repeat B through E until the entire buffer is filled or until all data within the page is loaded. While the lower bits in the address are mapped to words within the page, the higher bits address the pages within the FLASH. This is illustrated in Figure 28-2 on page 203. Note that if less than eight bits are required to address words in the page (pagesize < 256), the most significant bit(s) in the address low byte are used to address the page when performing a Page Write. G. Load Address High byte 1. Set XA1, XA0 to "00". This enables address loading. 2. Set BS1 to "1". This selects high address. 3. Set DATA = Address high byte (0x00 - 0xFF). 4. Give XTAL1 a positive pulse. This loads the address high byte.
202
ATmega406
2548E-AVR-07/06
ATmega406
H. Program Page 1. Give WR a negative pulse. This starts programming of the entire page of data. RDY/BSY goes low. 2. Wait until RDY/BSY goes high (See Figure 28-3 for signal waveforms). I. Repeat B through H until the entire Flash is programmed or until all data has been programmed. J. End Page Programming 1. 1. Set XA1, XA0 to "10". This enables command loading. 2. Set DATA to "0000 0000". This is the command for No Operation. 3. Give XTAL1 a positive pulse. This loads the command, and the internal write signals are reset. Figure 28-2. Addressing the Flash Which is Organized in Pages(1)
PCMSB PROGRAM COUNTER
PCPAGE
PAGEMSB
PCWORD
PAGE ADDRESS WITHIN THE FLASH PROGRAM MEMORY
PAGE
WORD ADDRESS WITHIN A PAGE
PAGE INSTRUCTION WORD PCWORD[PAGEMSB:0]: 00 01 02
PAGEEND
Note:
1. PCPAGE and PCWORD are listed in Table 28-5 on page 198.
203
2548E-AVR-07/06
Figure 28-3. Programming the Flash Waveforms(1)
F
A
DATA 0x10
B
ADDR. LOW
C
DATA LOW
D
DATA HIGH
E
XX
B
ADDR. LOW
C
DATA LOW
D
DATA HIGH
E
XX
G
ADDR. HIGH
H
XX
XA1
XA0
BS1
XTAL1
WR
RDY/BSY
RESET +12V
OE
PAGEL
BS2
Note:
1. "XX" is don't care. The letters refer to the programming description above.
28.6.6
Programming the EEPROM The EEPROM is organized in pages, see Table 28-6 on page 198. When programming the EEPROM, the program data is latched into a page buffer. This allows one page of data to be programmed simultaneously. The programming algorithm for the EEPROM data memory is as follows (refer to "Programming the Flash" on page 202 for details on Command, Address and Data loading): 1. A: Load Command "0001 0001". 2. G: Load Address High Byte (0x00 - 0xFF). 3. B: Load Address Low Byte (0x00 - 0xFF). 4. C: Load Data (0x00 - 0xFF). 5. E: Latch data (give PAGEL a positive pulse). K: Repeat 3 through 5 until the entire buffer is filled. L: Program EEPROM page 1. Set BS to "0". 2. Give WR a negative pulse. This starts programming of the EEPROM page. RDY/BSY goes low. 3. Wait until to RDY/BSY goes high before programming the next page (See Figure 28-4 for signal waveforms).
204
ATmega406
2548E-AVR-07/06
ATmega406
Figure 28-4. Programming the EEPROM Waveforms
K
A
DATA 0x11
G
ADDR. HIGH
B
ADDR. LOW
C
DATA
E
XX
B
ADDR. LOW
C
DATA
E
XX
L
XA1
XA0
BS1
XTAL1
WR
RDY/BSY
RESET +12V
OE
PAGEL
BS2
28.6.7
Reading the Flash The algorithm for reading the Flash memory is as follows (refer to "Programming the Flash" on page 202 for details on Command and Address loading): 1. A: Load Command "0000 0010". 2. G: Load Address High Byte (0x00 - 0xFF). 3. B: Load Address Low Byte (0x00 - 0xFF). 4. Set OE to "0", and BS1 to "0". The Flash word low byte can now be read at DATA. 5. Set BS to "1". The Flash word high byte can now be read at DATA. 6. Set OE to "1".
28.6.8
Reading the EEPROM The algorithm for reading the EEPROM memory is as follows (refer to "Programming the Flash" on page 202 for details on Command and Address loading): 1. A: Load Command "0000 0011". 2. G: Load Address High Byte (0x00 - 0xFF). 3. B: Load Address Low Byte (0x00 - 0xFF). 4. Set OE to "0", and BS1 to "0". The EEPROM Data byte can now be read at DATA. 5. Set OE to "1".
205
2548E-AVR-07/06
28.6.9
Programming the Fuse Low Bits The algorithm for programming the Fuse Low bits is as follows (refer to "Programming the Flash" on page 202 for details on Command and Data loading): 1. A: Load Command "0100 0000". 2. C: Load Data Low Byte. Bit n = "0" programs and bit n = "1" erases the Fuse bit. 3. Give WR a negative pulse and wait for RDY/BSY to go high.
28.6.10
Programming the Fuse High Bits The algorithm for programming the Fuse High bits is as follows (refer to "Programming the Flash" on page 202 for details on Command and Data loading): 1. A: Load Command "0100 0000". 2. C: Load Data Low Byte. Bit n = "0" programs and bit n = "1" erases the Fuse bit. 3. Set BS1 to "1" and BS2 to "0". This selects high data byte. 4. Give WR a negative pulse and wait for RDY/BSY to go high. 5. Set BS1 to "0". This selects low data byte. Figure 28-5. Programming the FUSES Waveforms
Write Fuse Low byte A
DATA
0x40
Write Fuse high byte A C
DATA XX
C
DATA XX
0x40
XA1
XA0
BS1
BS2
XTAL1
WR
RDY/BSY
RESET +12V
OE
PAGEL
28.6.11
Programming the Lock Bits The algorithm for programming the Lock bits is as follows (refer to "Programming the Flash" on page 202 for details on Command and Data loading): 1. A: Load Command "0010 0000". 2. C: Load Data Low Byte. Bit n = "0" programs the Lock bit. If LB mode 3 is programmed (LB1 and LB2 is programmed), it is not possible to program the Boot Lock bits by any External Programming mode. 3. Give WR a negative pulse and wait for RDY/BSY to go high. The Lock bits can only be cleared by executing Chip Erase.
206
ATmega406
2548E-AVR-07/06
ATmega406
28.6.12 Reading the Fuse and Lock Bits The algorithm for reading the Fuse and Lock bits is as follows (refer to "Programming the Flash" on page 202 for details on Command loading): 1. A: Load Command "0000 0100". 2. Set OE to "0", BS2 to "0" and BS1 to "0". The status of the Fuse Low bits can now be read at DATA ("0" means programmed). 3. Set OE to "0", BS2 to "1" and BS1 to "1". The status of the Fuse High bits can now be read at DATA ("0" means programmed). 4. Set OE to "0", BS2 to "0" and BS1 to "1". The status of the Lock bits can now be read at DATA ("0" means programmed). 5. Set OE to "1". Figure 28-6. Mapping Between BS1, BS2 and the Fuse and Lock Bits During Read
Fuse Low Byte 0
0 0 BS2 Lock Bits 0 1 BS1 1 DATA
Fuse High Byte BS2
1
28.6.13
Reading the Signature Bytes The algorithm for reading the Signature bytes is as follows (refer to "Programming the Flash" on page 202 for details on Command and Address loading): 1. A: Load Command "0000 1000". 2. B: Load Address Low Byte (0x00 - 0x02). 3. Set OE to "0", and BS to "0". The selected Signature byte can now be read at DATA. 4. Set OE to "1".
28.6.14
Reading the Calibration Byte The algorithm for reading the Calibration byte is as follows (refer to "Programming the Flash" on page 202 for details on Command and Address loading): 1. A: Load Command "0000 1000". 2. B: Load Address Low Byte, 0x00. 3. Set OE to "0", and BS1 to "1". The Calibration byte can now be read at DATA. 4. Set OE to "1".
207
2548E-AVR-07/06
28.6.15
Parallel Programming Characteristics Figure 28-7. Parallel Programming Timing, Including some General Timing Requirements
tXLWL XTAL1 tDVXH Data & Contol (DATA, XA0/1, BS1, BS2) tBVPH PAGEL WR RDY/BSY tWLRH tPHPL tWLWH tPLWL
WLRL
tXHXL tXLDX
tPLBX t BVWL
tWLBX
Figure 28-8. Parallel Programming Timing, Loading Sequence with Timing Requirements(1)
LOAD ADDRESS (LOW BYTE) LOAD DATA (LOW BYTE)
t XLXH
LOAD DATA LOAD DATA (HIGH BYTE)
tXLPH tPLXH
LOAD ADDRESS (LOW BYTE)
XTAL1
BS1
PAGEL
DATA
ADDR0 (Low Byte)
DATA (Low Byte)
DATA (High Byte)
ADDR1 (Low Byte)
XA0
XA1
Note:
1. The timing requirements shown in Figure 28-7 (i.e., tDVXH, tXHXL, and tXLDX) also apply to loading operation.
208
ATmega406
2548E-AVR-07/06
ATmega406
Figure 28-9. Parallel Programming Timing, Reading Sequence (within the Same Page) with Timing Requirements(1)
LOAD ADDRESS (LOW BYTE)
tXLOL
READ DATA (LOW BYTE)
READ DATA (HIGH BYTE)
LOAD ADDRESS (LOW BYTE)
XTAL1
tBVDV
BS1
tOLDV
OE
tOHDZ
DATA
ADDR0 (Low Byte)
DATA (Low Byte)
DATA (High Byte)
ADDR1 (Low Byte)
XA0
XA1
Note:
1. The timing requirements shown in Figure 28-7 (i.e., tDVXH, tXHXL, and tXLDX) also apply to reading operation.
209
2548E-AVR-07/06
Table 28-11. Parallel Programming Characteristics
Symbol VPP IPP tDVXH tXLXH tXHXL tXLDX tXLWL tXLPH tPLXH tBVPH tPHPL tPLBX tWLBX tPLWL tBVWL tWLWH tWLRL tWLRH tWLRH_CE tXLOL tBVDV tOLDV tOHDZ Notes: 1. Parameter Programming Enable Voltage (RESET input) Programming Enable Current Data and Control Valid before XTAL1 High XTAL1 Low to XTAL1 High XTAL1 Pulse Width High Data and Control Hold after XTAL1 Low XTAL1 Low to WR Low XTAL1 Low to PAGEL high PAGEL low to XTAL1 high BS1 Valid before PAGEL High PAGEL Pulse Width High BS1 Hold after PAGEL Low BS2/1 Hold after WR Low PAGEL Low to WR Low BS1 Valid to WR Low WR Pulse Width Low WR Low to RDY/BSY Low WR Low to RDY/BSY High(1) WR Low to RDY/BSY High for Chip Erase(2) XTAL1 Low to OE Low BS1 Valid to DATA valid OE Low to DATA Valid OE High to DATA Tri-stated 67 200 150 67 0 0 150 67 150 67 67 67 67 150 0 3.7 7.5 0 0 250 250 250 1 4.5 9 Min 11.5 Typ Max 12.5 250 Units V A ns ns ns ns ns ns ns ns ns ns ns ns ns ns s ms ms ns ns ns ns
tWLRH is valid for the Write Flash, Write EEPROM, Write Fuse bits and Write Lock bits commands. 2. tWLRH_CE is valid for the Chip Erase command.
210
ATmega406
2548E-AVR-07/06
ATmega406
28.7 Programming via the JTAG Interface
Programming through the JTAG interface requires control of the four JTAG specific pins: TCK, TMS, TDI, and TDO. Control of the reset and clock pins is not required. To be able to use the JTAG interface, the JTAGEN Fuse must be programmed. The device is default shipped with the fuse programmed. In addition, the JTD bit in MCUCSR must be cleared. Alternatively, if the JTD bit is set, the external reset can be forced low. Then, the JTD bit will be cleared after two chip clocks, and the JTAG pins are available for programming. This provides a means of using the JTAG pins as normal port pins in Running mode while still allowing In-System Programming via the JTAG interface. Note that this technique can not be used when using the JTAG pins for Boundary-scan or On-chip Debug. In these cases the JTAG pins must be dedicated for this purpose. As a definition in this datasheet, the LSB is shifted in and out first of all Shift Registers. 28.7.1 Programming Specific JTAG Instructions The instruction register is 4-bit wide, supporting up to 16 instructions. The JTAG instructions useful for programming are listed below. The OPCODE for each instruction is shown behind the instruction name in hex format. The text describes which data register is selected as path between TDI and TDO for each instruction. The Run-Test/Idle state of the TAP controller is used to generate internal clocks. It can also be used as an idle state between JTAG sequences. The state machine sequence for changing the instruction word is shown in Figure 28-10.
211
2548E-AVR-07/06
Figure 28-10. State Machine Sequence for Changing the Instruction Word
1 Test-Logic-Reset 0 0 Run-Test/Idle 1 Select-DR Scan 0 1 Capture-DR 0 Shift-DR 1 Exit1-DR 0 Pause-DR 1 0 Exit2-DR 1 Update-DR 1 0 0 0 1 0 1 1 Select-IR Scan 0 Capture-IR 0 Shift-IR 1 Exit1-IR 0 Pause-IR 1 Exit2-IR 1 Update-IR 1 0 0 1 0 1
28.7.2
AVR_RESET (0xC) The AVR specific public JTAG instruction for setting the AVR device in the Reset mode or taking the device out from the Reset mode. The TAP controller is not reset by this instruction. The one bit Reset Register is selected as data register. Note that the reset will be active as long as there is a logic "one" in the Reset Chain. The output from this chain is not latched. The active states are: * Shift-DR: The Reset Register is shifted by the TCK input.
28.7.3
PROG_ENABLE (0x4) The AVR specific public JTAG instruction for enabling programming via the JTAG port. The 16bit Programming Enable Register is selected as data register. The active states are the following: * Shift-DR: The programming enable signature is shifted into the data register. * Update-DR: The programming enable signature is compared to the correct value, and Programming mode is entered if the signature is valid.
212
ATmega406
2548E-AVR-07/06
ATmega406
28.7.4 PROG_COMMANDS (0x5) The AVR specific public JTAG instruction for entering programming commands via the JTAG port. The 15-bit Programming Command Register is selected as data register. The active states are the following: * Capture-DR: The result of the previous command is loaded into the data register. * Shift-DR: The data register is shifted by the TCK input, shifting out the result of the previous command and shifting in the new command. * Update-DR: The programming command is applied to the Flash inputs * Run-Test/Idle: One clock cycle is generated, executing the applied command (not always required, see Table 28-12 below). 28.7.5 PROG_PAGELOAD (0x6) The AVR specific public JTAG instruction to directly load the Flash data page via the JTAG port. An 8-bit Flash Data Byte Register is selected as the data register. This is physically the 8 LSBs of the Programming Command Register. The active states are the following: * Shift-DR: The Flash Data Byte Register is shifted by the TCK input. * Update-DR: The content of the Flash Data Byte Register is copied into a temporary register. A write sequence is initiated that within 11 TCK cycles loads the content of the temporary register into the Flash page buffer. The AVR automatically alternates between writing the low and the high byte for each new Update-DR state, starting with the low byte for the first UpdateDR encountered after entering the PROG_PAGELOAD command. The Program Counter is pre-incremented before writing the low byte, except for the first written byte. This ensures that the first data is written to the address set up by PROG_COMMANDS, and loading the last location in the page buffer does not make the program counter increment into the next page. 28.7.6 PROG_PAGEREAD (0x7) The AVR specific public JTAG instruction to directly capture the Flash content via the JTAG port. An 8-bit Flash Data Byte Register is selected as the data register. This is physically the 8 LSBs of the Programming Command Register. The active states are the following: * Capture-DR: The content of the selected Flash byte is captured into the Flash Data Byte Register. The AVR automatically alternates between reading the low and the high byte for each new Capture-DR state, starting with the low byte for the first Capture-DR encountered after entering the PROG_PAGEREAD command. The Program Counter is post-incremented after reading each high byte, including the first read byte. This ensures that the first data is captured from the first address set up by PROG_COMMANDS, and reading the last location in the page makes the program counter increment into the next page. * Shift-DR: The Flash Data Byte Register is shifted by the TCK input. 28.7.7 Data Registers The data registers are selected by the JTAG instruction registers described in section "Programming Specific JTAG Instructions" on page 211. The data registers relevant for programming operations are: * Reset Register * Programming Enable Register * Programming Command Register * Flash Data Byte Register
213
2548E-AVR-07/06
28.7.8
Reset Register The Reset Register is a Test Data Register used to reset the part during programming. It is required to reset the part before entering Programming mode. A high value in the Reset Register corresponds to pulling the external reset low. The part is reset as long as there is a high value present in the Reset Register. Depending on the Fuse settings for the clock options, the part will remain reset for a Reset Time-out period (refer to "Clock Sources" on page 26) after releasing the Reset Register. The output from this data register is not latched, so the reset will take place immediately, as shown in Figure 9-1 on page 40.
28.7.9
Programming Enable Register The Programming Enable Register is a 16-bit register. The contents of this register is compared to the programming enable signature, binary code 0b1010_0011_0111_0000. When the contents of the register is equal to the programming enable signature, programming via the JTAG port is enabled. The register is reset to 0 on Power-on Reset, and should always be reset when leaving Programming mode. Figure 28-11. Programming Enable Register
TDI
D A T A
0xA370
=
D
Q
Programming Enable
ClockDR & PROG_ENABLE
TDO
28.7.10
Programming Command Register The Programming Command Register is a 15-bit register. This register is used to serially shift in programming commands, and to serially shift out the result of the previous command, if any. The JTAG Programming Instruction Set is shown in Table 28-12. The state sequence when shifting in the programming commands is illustrated in Figure 28-13.
214
ATmega406
2548E-AVR-07/06
ATmega406
Figure 28-12. Programming Command Register
TDI
S T R O B E S
A D D R E S S / D A T A
Flash EEPROM Fuses Lock Bits
TDO
Table 28-12. JTAG Programming Instruction Set a = address high bits, b = address low bits, H = 0 - Low byte, 1 - High Byte, o = data out, i = data in, x = don't care
Instruction TDI Sequence 0100011_10000000 0110001_10000000 0110011_10000000 0110011_10000000 0110011_10000000 0100011_00010000 0000111_aaaaaaaa 0000011_bbbbbbbb 0010011_iiiiiiii 0010111_iiiiiiii 0110111_00000000 1110111_00000000 0110111_00000000 0110111_00000000 0110101_00000000 0110111_00000000 0110111_00000000 0110111_00000000 0100011_00000010 0000111_aaaaaaaa 0000011_bbbbbbbb TDO Sequence xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxox_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxox_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (9) (1) (9) (2) Notes
1a. Chip Erase
1b. Poll for Chip Erase Complete 2a. Enter Flash Write 2b. Load Address High Byte 2c. Load Address Low Byte 2d. Load Data Low Byte 2e. Load Data High Byte 2f. Latch Data
2g. Write Flash Page
(1)
2h. Poll for Page Write Complete 3a. Enter Flash Read 3b. Load Address High Byte 3c. Load Address Low Byte
(2)
215
2548E-AVR-07/06
Table 28-12. JTAG Programming Instruction (Continued) Set (Continued) a = address high bits, b = address low bits, H = 0 - Low byte, 1 - High Byte, o = data out, i = data in, x
Instruction 3d. Read Data Low and High Byte 4a. Enter EEPROM Write 4b. Load Address High Byte 4c. Load Address Low Byte 4d. Load Data Byte 4e. Latch Data TDI Sequence 0110010_00000000 0110110_00000000 0110111_00000000 0100011_00010001 0000111_aaaaaaaa 0000011_bbbbbbbb 0010011_iiiiiiii 0110111_00000000 1110111_00000000 0110111_00000000 0110011_00000000 0110001_00000000 0110011_00000000 0110011_00000000 0110011_00000000 0100011_00000011 0000111_aaaaaaaa 0000011_bbbbbbbb 0110011_bbbbbbbb 0110010_00000000 0110011_00000000 0100011_01000000
(6)
TDO Sequence xxxxxxx_xxxxxxxx xxxxxxx_oooooooo xxxxxxx_oooooooo xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxox_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_oooooooo xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxox_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxox_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx
Notes Low byte High byte
(9)
(1)
4f. Write EEPROM Page
(1)
4g. Poll for Page Write Complete 5a. Enter EEPROM Read 5b. Load Address High Byte 5c. Load Address Low Byte 5d. Read Data Byte 6a. Enter Fuse Write 6b. Load Data High Byte
(2)
(9)
0010011_iiiiiiii 0110111_00000000 0110101_00000000 0110111_00000000 0110111_00000000 0110111_00000000 0010011_iiiiiiii 0110011_00000000 0110001_00000000 0110011_00000000 0110011_00000000 0110011_00000000 0100011_00100000 0010011_11iiiiii
(3)
6c. Write Fuse High Byte
(1)
6d. Poll for Fuse Write Complete 6e. Load Data Low Byte(7)
(2) (3)
6f. Write Fuse Low Byte
(1)
6g. Poll for Fuse Write Complete 7a. Enter Lock Bit Write 7b. Load Data Byte(8)
(2)
(4)
216
ATmega406
2548E-AVR-07/06
ATmega406
Table 28-12. JTAG Programming Instruction (Continued) Set (Continued) a = address high bits, b = address low bits, H = 0 - Low byte, 1 - High Byte, o = data out, i = data in, x
Instruction TDI Sequence 0110011_00000000 0110001_00000000 0110011_00000000 0110011_00000000 0110011_00000000 0100011_00000100 0111110_00000000 0111111_00000000 0110010_00000000 0110011_00000000 0110110_00000000 0110111_00000000 0111010_00000000 0110010_00000000 0110110_00000000 0110111_00000000 0100011_00001000 0000011_bbbbbbbb 0110010_00000000 0110011_00000000 0100011_00001000 0000011_bbbbbbbb 0110110_00000000 0110111_00000000 0100011_00000000 0110011_00000000 TDO Sequence xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxox_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_oooooooo xxxxxxx_xxxxxxxx xxxxxxx_oooooooo xxxxxxx_xxxxxxxx xxxxxxx_xxoooooo xxxxxxx_xxxxxxxx xxxxxxx_oooooooo xxxxxxx_oooooooo xxxxxxx_oooooooo xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_oooooooo xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_oooooooo xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (5) (5) Fuse High byte Fuse Low byte Lock bits Notes
7c. Write Lock Bits
(1)
7d. Poll for Lock Bit Write complete 8a. Enter Fuse/Lock Bit Read 8b. Read Fuse High Byte(6) 8c. Read Fuse Low Byte(7) 8d. Read Lock Bits(8)
(2)
8e. Read Fuses and Lock Bits
9a. Enter Signature Byte Read 9b. Load Address Byte 9c. Read Signature Byte 10a. Enter Calibration Byte Read 10b. Load Address Byte 10c. Read Calibration Byte 11a. Load No Operation Command Notes:
1. This command sequence is not required if the seven MSB are correctly set by the previous command sequence (which is normally the case). 2. Repeat until o = "1". 3. Set bits to "0" to program the corresponding Fuse, "1" to unprogram the Fuse. 4. Set bits to "0" to program the corresponding Lock bit, "1" to leave the Lock bit unchanged. 5. "0" = programmed, "1" = unprogrammed. 6. The bit mapping for Fuses High byte is listed in Table 28-3 on page 196 7. The bit mapping for Fuses Low byte is listed in Table 28-4 on page 197 8. The bit mapping for Lock bits byte is listed in Table 28-1 on page 195 9. Address bits exceeding PCMSB and EEAMSB (Table 28-5 and Table 28-6) are don't care 10. All TDI and TDO sequences are represented by binary digits (0b...).
217
2548E-AVR-07/06
Figure 28-13. State Machine Sequence for Changing/Reading the Data Word
1 Test-Logic-Reset 0 0 Run-Test/Idle 1 Select-DR Scan 0 1 Capture-DR 0 Shift-DR 1 Exit1-DR 0 Pause-DR 1 0 Exit2-DR 1 Update-DR 1 0 0 0 1 0 1 1 Select-IR Scan 0 Capture-IR 0 Shift-IR 1 Exit1-IR 0 Pause-IR 1 Exit2-IR 1 Update-IR 1 0 0 1 0 1
28.7.11
Flash Data Byte Register The Flash Data Byte Register provides an efficient way to load the entire Flash page buffer before executing Page Write, or to read out/verify the content of the Flash. A state machine sets up the control signals to the Flash and senses the strobe signals from the Flash, thus only the data words need to be shifted in/out. The Flash Data Byte Register actually consists of the 8-bit scan chain and a 8-bit temporary register. During page load, the Update-DR state copies the content of the scan chain over to the temporary register and initiates a write sequence that within 11 TCK cycles loads the content of the temporary register into the Flash page buffer. The AVR automatically alternates between writing the low and the high byte for each new Update-DR state, starting with the low byte for the first Update-DR encountered after entering the PROG_PAGELOAD command. The Program Counter is pre-incremented before writing the low byte, except for the first written byte. This ensures that the first data is written to the address set up by PROG_COMMANDS, and loading the last location in the page buffer does not make the Program Counter increment into the next page. During Page Read, the content of the selected Flash byte is captured into the Flash Data Byte Register during the Capture-DR state. The AVR automatically alternates between reading the low and the high byte for each new Capture-DR state, starting with the low byte for the first Cap-
218
ATmega406
2548E-AVR-07/06
ATmega406
ture-DR encountered after entering the PROG_PAGEREAD command. The Program Counter is post-incremented after reading each high byte, including the first read byte. This ensures that the first data is captured from the first address set up by PROG_COMMANDS, and reading the last location in the page makes the program counter increment into the next page. Figure 28-14. Flash Data Byte Register
STROBES
TDI
State Machine
ADDRESS
Flash EEPROM Fuses Lock Bits
D A T A
TDO
The state machine controlling the Flash Data Byte Register is clocked by TCK. During normal operation in which eight bits are shifted for each Flash byte, the clock cycles needed to navigate through the TAP controller automatically feeds the state machine for the Flash Data Byte Register with sufficient number of clock pulses to complete its operation transparently for the user. However, if too few bits are shifted between each Update-DR state during page load, the TAP controller should stay in the Run-Test/Idle state for some TCK cycles to ensure that there are at least 11 TCK cycles between each Update-DR state. 28.7.12 Programming Algorithm All references below of type "1a", "1b", and so on, refer to Table 28-12. Entering Programming Mode 1. Enter JTAG instruction AVR_RESET and shift 1 in the Reset Register. 2. Enter instruction PROG_ENABLE and shift 0b1010_0011_0111_0000 in the Programming Enable Register. 28.7.14 Leaving Programming Mode 1. Enter JTAG instruction PROG_COMMANDS. 2. Disable all programming instructions by using no operation instruction 11a. 3. Enter instruction PROG_ENABLE and shift 0b0000_0000_0000_0000 in the programming Enable Register. 4. Enter JTAG instruction AVR_RESET and shift 0 in the Reset Register.
28.7.13
219
2548E-AVR-07/06
28.7.15
Performing Chip Erase 1. Enter JTAG instruction PROG_COMMANDS. 2. Start Chip Erase using programming instruction 1a. 3. Poll for Chip Erase complete using programming instruction 1b, or wait for tWLRH_CE (refer to Table 28-11 on page 210).
28.7.16
Programming the Flash 1. Enter JTAG instruction PROG_COMMANDS. 2. Enable Flash write using programming instruction 2a. 3. Load address High byte using programming instruction 2b. 4. Load address Low byte using programming instruction 2c. 5. Load data using programming instructions 2d, 2e and 2f. 6. Repeat steps 4 and 5 for all instruction words in the page. 7. Write the page using programming instruction 2g. 8. Poll for Flash write complete using programming instruction 2h, or wait for tWLRH (refer to Table 28-11 on page 210). 9. Repeat steps 3 to 7 until all data have been programmed. A more efficient data transfer can be achieved using the PROG_PAGELOAD instruction: 1. Enter JTAG instruction PROG_COMMANDS. 2. Enable Flash write using programming instruction 2a. 3. Load the page address using programming instructions 2b and 2c. PCWORD (refer to Table 28-5 on page 198) is used to address within one page and must be written as 0. 4. Enter JTAG instruction PROG_PAGELOAD. 5. Load the entire page by shifting in all instruction words in the page byte-by-byte, starting with the LSB of the first instruction in the page and ending with the MSB of the last instruction in the page. Use Update-DR to copy the contents of the Flash Data Byte Register into the Flash page location and to auto-increment the Program Counter before each new word. 6. Enter JTAG instruction PROG_COMMANDS. 7. Write the page using programming instruction 2g. 8. Poll for Flash write complete using programming instruction 2h, or wait for tWLRH (refer to Table 28-11 on page 210). 9. Repeat steps 3 to 8 until all data have been programmed.
28.7.17
Reading the Flash 1. Enter JTAG instruction PROG_COMMANDS. 2. Enable Flash read using programming instruction 3a. 3. Load address using programming instructions 3b and 3c. 4. Read data using programming instruction 3d. 5. Repeat steps 3 and 4 until all data have been read. A more efficient data transfer can be achieved using the PROG_PAGEREAD instruction: 1. Enter JTAG instruction PROG_COMMANDS. 2. Enable Flash read using programming instruction 3a. 3. Load the page address using programming instructions 3b and 3c. PCWORD (refer to Table 28-5 on page 198) is used to address within one page and must be written as 0.
220
ATmega406
2548E-AVR-07/06
ATmega406
4. Enter JTAG instruction PROG_PAGEREAD. 5. Read the entire page (or Flash) by shifting out all instruction words in the page (or Flash), starting with the LSB of the first instruction in the page (Flash) and ending with the MSB of the last instruction in the page (Flash). The Capture-DR state both captures the data from the Flash, and also auto-increments the program counter after each word is read. Note that Capture-DR comes before the shift-DR state. Hence, the first byte which is shifted out contains valid data. 6. Enter JTAG instruction PROG_COMMANDS. 7. Repeat steps 3 to 6 until all data have been read. 28.7.18 Programming the EEPROM 1. Enter JTAG instruction PROG_COMMANDS. 2. Enable EEPROM write using programming instruction 4a. 3. Load address High byte using programming instruction 4b. 4. Load address Low byte using programming instruction 4c. 5. Load data using programming instructions 4d and 4e. 6. Repeat steps 4 and 5 for all data bytes in the page. 7. Write the data using programming instruction 4f. 8. Poll for EEPROM write complete using programming instruction 4g, or wait for tWLRH (refer to Table 28-11 on page 210). 9. Repeat steps 3 to 8 until all data have been programmed. Note that the PROG_PAGELOAD instruction can not be used when programming the EEPROM. 28.7.19 Reading the EEPROM 1. Enter JTAG instruction PROG_COMMANDS. 2. Enable EEPROM read using programming instruction 5a. 3. Load address using programming instructions 5b and 5c. 4. Read data using programming instruction 5d. 5. Repeat steps 3 and 4 until all data have been read. Note that the PROG_PAGEREAD instruction can not be used when reading the EEPROM. 28.7.20 Programming the Fuses 1. Enter JTAG instruction PROG_COMMANDS. 2. Enable Fuse write using programming instruction 6a. 3. Load data high byte using programming instructions 6b. A bit value of "0" will program the corresponding fuse, a "1" will unprogram the fuse. 4. Write Fuse High byte using programming instruction 6c. 5. Poll for Fuse write complete using programming instruction 6d, or wait for tWLRH (refer to Table 28-11 on page 210). 6. Load data low byte using programming instructions 6e. A "0" will program the fuse, a "1" will unprogram the fuse. 7. Write Fuse low byte using programming instruction 6f. 8. Poll for Fuse write complete using programming instruction 6g, or wait for tWLRH (refer to Table 28-11 on page 210).
221
2548E-AVR-07/06
28.7.21
Programming the Lock Bits 1. Enter JTAG instruction PROG_COMMANDS. 2. Enable Lock bit write using programming instruction 7a. 3. Load data using programming instructions 7b. A bit value of "0" will program the corresponding lock bit, a "1" will leave the lock bit unchanged. 4. Write Lock bits using programming instruction 7c. 5. Poll for Lock bit write complete using programming instruction 7d, or wait for tWLRH (refer to Table 28-11 on page 210).
28.7.22
Reading the Fuses and Lock Bits 1. Enter JTAG instruction PROG_COMMANDS. 2. Enable Fuse/Lock bit read using programming instruction 8a. 3. To read all Fuses and Lock bits, use programming instruction 8e. To only read Fuse High byte, use programming instruction 8b. To only read Fuse Low byte, use programming instruction 8c. To only read Lock bits, use programming instruction 8d.
28.7.23
Reading the Signature Bytes 1. Enter JTAG instruction PROG_COMMANDS. 2. Enable Signature byte read using programming instruction 9a. 3. Load address 0x00 using programming instruction 9b. 4. Read first signature byte using programming instruction 9c. 5. Repeat steps 3 and 4 with address 0x01 and address 0x02 to read the second and third signature bytes, respectively.
28.7.24
Reading the Calibration Byte 1. Enter JTAG instruction PROG_COMMANDS. 2. Enable Calibration byte read using programming instruction 10a. 3. Load address 0x00 using programming instruction 10b. 4. Read the calibration byte using programming instruction 10c.
222
ATmega406
2548E-AVR-07/06
ATmega406
29. Operating Circuit
Figure 29-1. Operating Circuit Diagram
Rpc
Rpf
+
Rdf Rcf
OD RN PVT Rled RP PV4 PB1 CP PB2 RP PV3 CP RP PV2 CP SCK RP CP RP PV1 SDA 100 SMB Data 100 SMB Clock PB3 PB4 Rled Rled Rled PB0 Rled OC OPC VFET BATT
NV RP1 RP2
Rppi PPI Ci
ATmega406
Rpi PI Rsense Rni NI Ci
VREG V CC
CREG 1
CREG 2
Ci
Rnni NNI RT4 PA4 CXTAL 2 RT3 PA3 RT2 PA2 RT1 PA1 RESET CRESET XTAL2 XTAL1 CXTAL2
PA0/ADC0 VREF VREFGND SGND GND
R1
CREF
223
2548E-AVR-07/06
Table 29-1.
Recommended values for external devices
Symbol R1 RT1 RT2 RT3 RT4 RS Rnni Rppi Rni Rpi Ci (Rpi-Rni)*Ci Rsense(1) RP CP RP*CP RN Rdf Rcf Rpf Rpc(2) CREF CREG1 CREG2 RP1 RP2 CRESET Note:
Use Pull-up resistor for thermistors
Parameter R R@25C
Min
Typ 10 10
Max
unit k k
NTC Thermistor B-constant Source Impedance when using PA0...4 as V-ADC inputs Current protection LP-filter resistor Current sense LP-filter resistors Current sense LP-filter capasitor Current sense LP-filter time constant Current sense resistor Cell input LP-filter resistor Cell input LP-filter capacitor Cell input LP-filter time constant Pull-up resistor Pull-up resistors Pre-charge resistor VREF decoupling VREG charge-storage R Worst Gain-error due to RS R R C R R C R R R C C 1 TWI Pull-up resistors C C 2.2 0.1 M F 1 10 0.01 6.5 0 10 0.01 3000 0 0 3 1 1 100 0.1 10 5 500 0.1 25 10 1 1 1 0.1 F 22 1000 0.5 100 TBD 500 0.4 20 4000 7 2 K k % k F s m F s M k F
1. The sense resistor should be adjusted to the current flow for the application. 2. The pre-charger resistor should be adjusted to the pre-charger curret flow for the application.
224
ATmega406
2548E-AVR-07/06
ATmega406
30. Electrical Characteristics
30.1 Absolute Maximum Ratings*
*NOTICE: Stresses beyond those listed under "Absolute Maximum Ratings" may cause permanent damage to the device. This is a stress rating only and functional operation of the device at these or other conditions beyond those indicated in the operational sections of this specification is not implied. Exposure to absolute maximum rating conditions for extended periods may affect device reliability.
Operating Temperature.................................... -30C to +85C Storage Temperature ..................................... -65C to +150C Voltage on PA0 - PA7, PB0 - PB7, PD0 - PD1, VCC, PI, PPI, NI, NNI, XTAL1, and XTAL2 with respect to Ground ............................. -0.5V to VREG +0.5V Voltage on SCL, SDA, NV, PV1 and RESET with respect to Ground .....................................-0.5V to + 6.0V Voltage on PVT and VFET with respect to Ground ......................................-0.5V to + 35V Voltage on PC0, OPC, OC and BATT with respect to Ground ...........................-0.5V to VFET + 0.5V Voltage on OD, PV2 - PV4 with respect to Ground .............................-0.5V to PVT + 0.5V Maximum Operating Voltage ............................................. 25V
30.2
DC Characteristics
DC Characteristics, TA = -30C to 85C, VCC = 3.3V
Parameter Condition Active Idle ADC Noise Reduction Supply Current Power Supply Current Power-save Power-down Power-off Regulated Output Voltage(2) IOUT = 5 mA IOUT = 5 mA TA = 0 - 60 C IOUT = 5 mA TA = -30 - 85 C Load Regulation Line Regulation Reference voltage VREF Ref. Voltage Accuracy Temperature Drift(4) After calibration, at calibration temperature TA = -30 - 60 C 0.1 mA < IOUT < 5 mA 4V < VFET < 25V, IOUT = 1 mA 3.25 35 20 1.5 3.3 5 20 20 2 1.1 0.1 80 0.2 3.35 15 70 60 10 Min Typ 1.2 270 220 Max Unit mA A A A A A V mV mV mV mV V % ppm/C
Voltage Regulator(1)
Temperature Stability
(2)
225
2548E-AVR-07/06
DC Characteristics, TA = -30C to 85C, VCC = 3.3V (Continued)
Parameter Reference Voltage Conversion Time Effective Resolution 1 LSB Un-scaled Inputs 1 LSB Scaled Inputs (x 0.2) INL ADC0, ADC1, ADC2, ADC3, VTEMP ADC4 Input Voltage Range CELL1 CELL2, PV1 2V CELL3, PV1 2V CELL4, PV1 2V Offset Gain Error Cell Inputs Reference Voltage Conversion Time and Resolution CC-ADC INL CC-ADC Offset
(7) (5) (6)
Condition
Min
Typ 1.100 519 12 269 1.34 1
Max
Unit V s Bits V mV
3 1 5 5 5 5 5
LSB V V V V V V mV
0 0 2 0 0 0 1.6 1 220
V-ADC
0.5
% mV ms
53.7 V Resolution 1.68 V Resolution 1000 ms conversion time Uncompensated TA = 0 - 60C 125
3.9 1000 4 50 1 200 15 1 0.6 4 11 15 10 50
ms LSB V V % mV/K K V s
CC-ADC Offset Drift CC-ADC Gain Error Temperature Sensor
VPTAT, Voltage Proportional to Absolute Temperature Absolute Accuracy(3) |VGS_ON| OC/OD Rise time (10 - 90%) (Switching OFF) OC/OD Fall time (VGS = 0 - VGS = -5V) (Switching ON) OPC Rise time (10 - 90%) (Switching OFF) OPC Fall time (VGS = 0 - VGS = -5V) (Switching ON) CL = 10 nF
CL = 10 nF
100
s
FET Driver
CL = 1 nF
100
500
s
CL = 1 nF
100
500
s
226
ATmega406
2548E-AVR-07/06
ATmega406
DC Characteristics, TA = -30C to 85C, VCC = 3.3V (Continued)
Parameter Slow RC Oscillator Ultra Low Power RC Oscillator Notes: Frequency Temperature Drift Frequency Temperature Drift TA = - 30 - 85C Condition TA = - 30 - 85C Min Typ 165 5 124 8 Max Unit kHz % kHz %
1. Voltage Regulator performance is based on 1 F smooth capacitor. 2. After VREF calibration at second temperature. By default the first calibration is performed at 85 C in Atmel factory test. The second calibration step can easily be implemented in a standard test flow at room temperature. 3. The measured VPTAT voltage must be scaled with the calibration value stored in the VPTAT Calibration Register to get the absolute temperature. The design target accuracy for this parameter assumes an exact calibration temperature. Actual accuracy of this parameter after calibration in Atmel factory test remains to be determined. 4. This value is not tested in production. 5. After system offset compensation in software. 6. After software gain error compensation. 7. This value should be measured at system level and stored in EEPROM for software offset compensation.
227
2548E-AVR-07/06
30.3
30.3.1
General I/O Lines characteristics
Low voltage ports
Figure 30-1. TA = -30C to 85C, VCC = 3.3V (unless otherwise noted) (1)
Symbol VIL VIH VOL VOH IIL IIH Notes: 1. 2. 3. 4. Parameter Input Low Voltage Input High Voltage Output Low Voltage
(4) (5)
Condition VCC = 3.3V VCC = 3.3V IOL = 5mA, VCC = 3.3V IOH = 2 mA, VCC = 3.3V VCC = 3.3V, pin low (absolute value) VCC = 3.3V, pin high (absolute value)
Min. -0.5 0.6VCC(3)
Typ.
Max. 0.3VCC(2) VCC + 0.5 0.5
Units V V V V
Output High Voltage Input Leakage Current I/O Pin Input Leakage Current I/O Pin
2.3 1 1
A A
Applicable for all except PC0. "Max" means the highest value where the pin is guaranteed to be read as low. "Min" means the lowest value where the pin is guaranteed to be read as high. Although each I/O port can sink more than the test conditions (5 mA at VCC = 3.3V) under steady state conditions (non-transient, the following must be observed: - The sum of all IOL should not exceed 20 mA. If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater than the listed test condition. 5. Although each I/O port can source more than the test conditions (2 mA at VCC = 3.3V) under steady state conditions (nontransient, the following must be observed: - The sum of all IOH should not exceed 2 mA.
30.3.2
High voltage ports
Figure 30-2. TA = -30C to 85C, VCC = 3.3V (unless otherwise noted)
Symbol VOL tr(1) tof(1) Notes:
(1)
Parameter Output Low Voltage Rise Time Output Fall Time from VIHmin to VILmax
Condition VCC = 3.3V VCC = 3.3V Cb < 400 pF(2)
Min.
Typ.
Max. 0.5 300 200
Units V ns ns
1. Parameter characterized and not tested. 2. Cb = capacitance of one bus line in pF
228
ATmega406
2548E-AVR-07/06
ATmega406
30.4 2-wire Serial Interface Characteristics
Table 30-1 describes the requirements for devices connected to the Two-wire Serial Bus. The ATmega406 Two-wire Serial Interface meets or exceeds these requirements under the noted conditions. Timing symbols refer to Figure 30-3. Table 30-1.
Symbol
VIL VIH (1) VOL tr (1)
Two-wire Serial Bus Requirements
Parameter Input Low-voltage Input High-voltage Output Low-voltage Rise Time for both SDA and SCL Output Fall Time from VIHmin to VILmax Spikes Suppressed by Input Filter Input Current each I/O Pin Capacitance for each I/O Pin SCL Clock Frequency Value of Pull-up resistor Hold Time (repeated) START Condition Low Period of the SCL Clock High period of the SCL clock Set-up time for a repeated START condition Data hold time Data setup time Setup time for STOP condition Bus free time between a STOP and START condition fCK(3) > max(16fSCL, 450 kHz)(4) fSCL 100 kHz fSCL 100 kHz fSCL 100 kHz fSCL 100 kHz fSCL 100 kHz fSCL 100 kHz fSCL 100 kHz fSCL 100 kHz fSCL 100 kHz 0.1VBUS < Vi < 0.9VBUS Cb < 400 pF
(2)
Condition
Min -0.5 2.1
Max 0.8 5.5 0.4 300 250
Units V V V ns ns ns A pF kHz s s s s s ns s s
350 A sink current
0
(1) tof (1) tSP
0 -5 - 0 V BUS - 0,4V -----------------------------350A 4.0 4.7 4.0 4.7 0.3 250 4.0 4.7
50 5 10 100 V BUS - 0,4V -----------------------------100A - - - - 3.45 - - -
Ii Ci(1) fSCL Rp tHD;STA tLOW tHIGH tSU;STA tHD;DAT tSU;DAT tSU;STO tBUF Notes: 1. 2. 3. 4.
In ATmega406, this parameter is characterized and not tested. Cb = capacitance of one bus line in pF. fCK = CPU clock frequency This requirement applies to all ATmega406 Two-wire Serial Interface operation. Other devices connected to the Two-wire Serial Bus need only obey the general fSCL requirement.
229
2548E-AVR-07/06
Figure 30-3. Two-wire Serial Bus Timing
tof tLOW SCL tSU;STA SDA tHD;STA tHD;DAT tSU;DAT tSU;STO tHIGH tLOW tr
tBUF
30.5
Reset Characteristics
Characteristics for Powering-up the LDO(1)
Parameter Charger Present VROT VCHT Regulator Power-on Threshold Charge Voltage Threshold No Charger Present VROT VPVIT Regulator Power-on Threshold Voltage Threshold on Battery Cell 1 3.0 2.0 4.0 V V 3.0 1.0 4.0 V V Min Typ Max Units
Table 30-2.
Symbol(2)
Notes:
1. Power-on Reset is issued when a charger is connected and the regulator has stable work conditions. 2. Values based on characterization.
Table 30-3.
Symbol VCOT Note:
Power-on Reset Characteristics
Parameter Charger-on Thresholt Voltage Condition Regulator must operate Min 6 Typ 7 Max 8 Units V
Internal Voltage Regulator must be on.
Table 30-4.
Symbol VRST tRST Note:
External Reset Characteristics
Parameter RESET Pin Threshold Voltage Minimum pulse width on RESET Pin Condition VREG = 3.3V Min 0.66 900 Typ Max 2.8 Units V ns
Internal Voltage Regulator must be on.
230
ATmega406
2548E-AVR-07/06
ATmega406
30.6 Supply Current of I/O Modules
Table 30-5 on page 231 is showing the additional current consumption compared to ICC Active and ICC Idle for every I/O module controlled by the Power Reduction Register, see "PRR0 - Power Reduction Register 0" on page 36 for details. The tables and formulas below can be used to calculate the additional current consumption for the different I/O modules in Active and Idle mode.
Table 30-5.
Additional Current Consumption for the different I/O modules
Additional Current Consumption at VCC = 3.3V, F = 1 MHZ [A] 68.0 4.5 6.0 5.0 Additional Current Consumption compared to Active mode [%] 5.6 0.4 0.5 4.2 Additional Current Consumption compared to Idle mode [%] 25.2 1.7 2.2 1.9
PRR0 bit PRTWI PRTIM1 PRTIM0 PRVADC
30.6.0.1
Example 1 Calculate the expected current consumption in idle mode with TIMER1, V-ADC and Battery Protection enabled at VCC = 3.3V and F = 1MHz. From Table 30-5, fourth column, we see that we need to add 1.7% for the TIMER1, 1.9% for the V-ADC, and 25.2% for the TWI module. Reading from "DC Characteristics" on page 225, we find that the idle current consumption is typically 1.2 mA at VCC = 3.3V and F = 1MHz. The total current consumption in idle mode with USART0, TIMER1, and SPI enabled, gives:
ICCtotal 1.2mA * ( 1 + 0.017 + 0.019 + 0.252 ) 1.55mA
231
2548E-AVR-07/06
31. Typical Characteristics - Preliminary
The following charts are tested on a few microcontrollers only. These figures are not tested during manufacturing, and are added for illustration purpose.
31.1
Pin Pull-up
Figure 31-1. I/O Pin Pull-Up Resistor Current vs. Input Voltage (VCC = 3.3V)
I/O PIN PULL-UP RESISTOR CURRENT vs. INPUT VOLTAGE
VCC = 3.3V
90 80 70 60
IOP (uA)
50 40 30 20 10 0 0 0,5 1 1,5 2 2,5 3 3,5
25 C 85 C -30 C
V I (V)
Figure 31-2. Reset Pull-Up Resistor Current vs. Input Voltage (VCC = 3.3V)
RESET PULL-UP RESISTOR CURRENT vs. RESET PIN VOLTAGE
VCC = 3.3V
80 70 60
IRESET(uA)
50 40 30 20 10 0 0 0,5 1 1,5 2 2,5 3 3,5
-30 C 25 C 85 C
VRESET(V)
232
ATmega406
2548E-AVR-07/06
ATmega406
31.2 Pin Driver Strength
Figure 31-3. I/O Pin Putput Voltage vs. Sink Current (VCC = 3.3V)
I/O PIN OUTPUT VOLTAGE vs. SINK CURRENT
VCC = 3.3V
1.3
85 C
1.2 1.1
25 C
1
-30 C
VOL (V)
0.9 0.8 0.7 0.6 0.5 0.4 0 5 10 15 20 25
IOL (mA)
Figure 31-4. I/O Pin output Voltage vs. Source Current (VCC = 3.3V)
I/O PIN OUTPUT VOLTAGE vs. SOURCE CURRENT
VCC = 3.3V
2.9
2.7
2.5
VOH (V)
2.3
2.1
1.9
-30 C 25 C 85 C
1.7
1.5 0 5 10 15 20 25
IOH (mA)
233
2548E-AVR-07/06
31.3
Internal Oscillator Speed
Figure 31-5. Watchdog Oscillator Frequency vs. Temperature (VCC = 3.3V)
WATCHDOG OSCILLATOR FREQUENCY vs. TEMPERATURE
VCC = 3.3 V
126 125 124 123
FRC (kHz)
122 121 120 119 118 117 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100
Temperature
Figure 31-6. Calibrated 1 MHz RC Oscillator Frequency vs. Temperature (VCC = 3.3V)
CALIBRATED 1 MHz RC OSCILLATOR FREQUENCY vs. TEMPERATURE
VCC = 3.3 V
1.025 1.02 1.015 1.01
FRC (MHz)
1.005 1 0.995 0.99 0.985 0.98 0.975 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100
Temperature
234
ATmega406
2548E-AVR-07/06
ATmega406
Figure 31-7. Calibrated 1 MHz RC Oscillator Frequency vs. OSCCAL Value (VCC = 3.3V)
CALIBRATED 1 MHz RC OSCILLATOR FREQUENCY vs. OSCCAL VALUE
2.5
85 C
2
25 C -30 C
FRC (MHz)
1.5
1
0.5
0 0 16 32 48 64 80 96 112 128 144 160 176 192 208 224 240 256
OSCCAL (X1)
Figure 31-8. Slow RC Oscillator Frequency vs. Temperature (VCC = 3.3V)
SLOW RC OSCILLATOR FREQUENCY vs. TEMPERATURE
VCC = 3.3 V
156.5
156
155.5
FRC (kHz)
155
154.5
154
153.5
153 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100
Temperature
235
2548E-AVR-07/06
32. Register Summary
Address
(0xFF) (0xFE) (0xFD) (0xFC) (0xFB) (0xFA) (0xF9) (0xF8) (0xF7) (0xF6) (0xF5) (0xF4) (0xF3) (0xF2) (0xF1) (0xF0) (0xEF) (0xEE) (0xED) (0xEC) (0xEB) (0xEA) (0xE9) (0xE8) (0xE7) (0xE6) (0xE5) (0xE4) (0xE3) (0xE2) (0xE1) (0xE0) (0xDF) (0xDE) (0xDD) (0xDC) (0xDB) (0xDA) (0xD9) (0xD8) (0xD7) (0xD6) (0xD5) (0xD4) (0xD3) (0xD2) (0xD1) (0xD0) (0xCF) (0xCE) (0xCD) (0xCC) (0xCB) (0xCA) (0xC9) (0xC8) (0xC7) (0xC6) (0xC5) (0xC4) (0xC3) (0xC2) (0xC1) (0xC0)
Name
Reserved Reserved Reserved Reserved Reserved Reserved Reserved BPPLR BPCR CBPTR BPOCD BPSCD BPDUV BPIR CBCR FCSR Reserved Reserved Reserved Reserved Reserved Reserved CADICH CADICL CADRDC CADRCC CADCSRB CADCSRA CADAC3 CADAC2 CADAC1 CADAC0 Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved BGCRR BGCCR Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved CCSR
Bit 7
- - - - - - - - -
Bit 6
- - - - - - - - - SCPT[3:0] DCDL[3:0]
Bit 5
- - - - - - - - -
Bit 4
- - - - - - - - -
Bit 3
- - - - - - - - DUVD
Bit 2
- - - - - - - - SCD
Bit 1
- - - - - - - BPPLE DCD OCPT[3:0] CCDL[3:0]
Bit 0
- - - - - - - BPPL CCD
Page
128 128 129 130 130 131
- - DUVIF - - - - - - - -
- - COCIF - - - - - - - -
- DUVT1 DOCIF - PWMOC - - - - - -
- DUVT0 SCIF - PWMOPC - - - - - - CADIC[15:8] CADIC[7:0] CADRDC[7:0] CADRCC[7:0] DUVIE CBE4 CPS - - - - - - COCIE CBE3 DFE - - - - - -
SCDL[3:0] DUDL[3:0] DOCIE CBE2 CFE - - - - - - SCIE CBE1 PFD - - - - - -
132 137 134
111 111 112 112 - CADACIF CADSI1 CADRCIF CADSI0 CADICIF CADSE 110 109 111 111 111 111 - - - - - - - - - - - - - - - - - - - - - - - - - - - - BGCR2 BGCC2 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - BGCR1 BGCC1 - - - - - - - - - - - - - - - XOE - - - - - - - - - - - - - - BGCR0 BGCC0 - - - - - - - - - - - - - - - ACS 29 123 123
- CADEN
CADACIE -
CADRCIE CADUB
CADICIE CADAS1
CADAS0
CADAC[31:24] CADAC[23:16] CADAC[15:8] CADAC[7:0] - - - - - - - - - - - - - - BGCR7 BGEN - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - BGCR6 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - BGCR5 BGCC5 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - BGCR4 BGCC4 - - - - - - - - - - - - - - - -
BGCR3 BGCC3 - - - - - - - - - - - - - - - -
236
ATmega406
2548E-AVR-07/06
ATmega406
Address
(0xBF) (0xBE) (0xBD) (0xBC) (0xBB) (0xBA) (0xB9) (0xB8) (0xB7) (0xB6) (0xB5) (0xB4) (0xB3) (0xB2) (0xB1) (0xB0) (0xAF) (0xAE) (0xAD) (0xAC) (0xAB) (0xAA) (0xA9) (0xA8) (0xA7) (0xA6) (0xA5) (0xA4) (0xA3) (0xA2) (0xA1) (0xA0) (0x9F) (0x9E) (0x9D) (0x9C) (0x9B) (0x9A) (0x99) (0x98) (0x97) (0x96) (0x95) (0x94) (0x93) (0x92) (0x91) (0x90) (0x8F) (0x8E) (0x8D) (0x8C) (0x8B) (0x8A) (0x89) (0x88) (0x87) (0x86) (0x85) (0x84) (0x83) (0x82) (0x81) (0x80) (0x7F) (0x7E)
Name
Reserved TWBCSR TWAMR TWCR TWDR TWAR TWSR TWBR Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved OCR1AH OCR1AL Reserved Reserved TCNT1H TCNT1L Reserved Reserved TCCR1B Reserved Reserved DIDR0
Bit 7
- TWBCIF TWINT
Bit 6
- TWBCIE TWEA
Bit 5
- - TWSTA
Bit 4
- - TWAM[6:0] TWSTO TWA[6:0]
Bit 3
- - TWWC
Bit 2
- TWBDT1 TWEN
Bit 1
- TWBDT0 -
Bit 0
- TWBCIP - TWIE TWGCE
Page
169 150 147 149 149 148 147
2-wire Serial Interface Data Register TWS[7:3] 2-wire Serial Interface Bit Rate Register - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TWPS1 TWPS0
Timer/Counter1 - Output Compare Register A High Byte Timer/Counter1 - Output Compare Register A Low Byte - - - - - - - - - - - - - - - -
101 101
Timer/Counter1 - Counter Register High Byte Timer/Counter1 - Counter Register Low Byte - - - - - - - - - - - - - - - - - - - - - - - - - - CTC1 - - VADC3D - - CS12 - - VADC2D - - CS11 - - VADC1D - - CS10 - - VADC0D
101 101
100
120
237
2548E-AVR-07/06
Address
(0x7D) (0x7C) (0x7B) (0x7A) (0x79) (0x78) (0x77) (0x76) (0x75) (0x74) (0x73) (0x72) (0x71) (0x70) (0x6F) (0x6E) (0x6D) (0x6C) (0x6B) (0x6A) (0x69) (0x68) (0x67) (0x66) (0x65) (0x64) (0x63) (0x62) (0x61) (0x60) 0x3F (0x5F) 0x3E (0x5E) 0x3D (0x5D) 0x3C (0x5C) 0x3B (0x5B) 0x3A (0x5A) 0x39 (0x59) 0x38 (0x58) 0x37 (0x57) 0x36 (0x56) 0x35 (0x55) 0x34 (0x54) 0x33 (0x53) 0x32 (0x52) 0x31 (0x51) 0x30 (0x50) 0x2F (0x4F) 0x2E (0x4E) 0x2D (0x4D) 0x2C (0x4C) 0x2B (0x4B) 0x2A (0x4A) 0x29 (0x49) 0x28 (0x48) 0x27 (0x47) 0x26 (0x46) 0x25 (0x45) 0x24 (0x44) 0x23 (0x43) 0x22 (0x42) 0x21 (0x41) 0x20 (0x40) 0x1F (0x3F) 0x1E (0x3E) 0x1D (0x3D) 0x1C (0x3C)
Name
Reserved VADMUX Reserved VADCSR VADCH VADCL Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved TIMSK1 TIMSK0 Reserved PCMSK1 PCMSK0 Reserved EICRA PCICR Reserved FOSCCAL Reserved PRR0 Reserved WUTCSR Reserved WDTCSR SREG SPH SPL Reserved Reserved Reserved Reserved Reserved SPMCSR Reserved MCUCR MCUSR SMCR Reserved OCDR Reserved Reserved Reserved Reserved Reserved GPIOR2 GPIOR1 Reserved OCR0B OCR0A TCNT0 TCCR0B TCCR0A GTCCR EEARH EEARL EEDR EECR GPIOR0 EIMSK EIFR
Bit 7
- - - - - - - - - - - - - - - -
Bit 6
- - - - - - - - - - - - - - - -
Bit 5
- - - - - - - - - - - - - - - -
Bit 4
- - - - -
Bit 3
- VADMUX3 - VADEN
Bit 2
- VADMUX2 - VADSC
Bit 1
- VADMUX1 - VADCCIF
Bit 0
- VADMUX0 - VADCCIE
Page
118 118 119 119
VADC Data Register High byte - - - - - - - - - - - PCINT[15:8] PCINT[7:0] - - - - - - - - - OCIE0B - - - - - - - - - OCIE1A OCIE0A - - - - - - - - - TOIE1 TOIE0 -
VADC Data Register Low byte - - - - - - - - - - -
102 93 59 59
- ISC31 - - - - - WUTIF - WDIF I SP15 SP7 - - - - - SPMIE - JTD - - - - - - - -
- ISC30 - - - - - WUTIE - WDIE T SP14 SP6 - - - - - RWWSB - - - - - - - - - -
- ISC21 - - - - - WUTCF - WDP3 H SP13 SP5 - - - - - SIGRD - - - - - - - - - -
- ISC20 - - - - - WUTR - WDCE S SP12 SP4 - - - - - RWWSRE - PUD JTRF - - - - - - -
- ISC11 - - - PRTWI - WUTE - WDE V SP11 SP3 - - - - - BLBSET - - WDRF SM2 - - - - - -
- ISC10 - - - PRTIM1 - WUTP2 - WDP2 N SP10 SP2 - - - - - PGWRT - - BODRF SM1 - - - - - -
- ISC01 PCIE1 - - PRTIM0 - WUTP1 - WDP1 Z SP9 SP1 - - - - - PGERS - IVSEL EXTRF SM0 - - - - - -
- ISC00 PCIE0 - 29 - PRVADC - WUTP0 - WDP0 C SP8 SP0 - - - - - SPMEN - IVCE PORF SE - 176 - - - - - 24 24 55/73/176 46 31 183 47 10 12 12 49 36 56 58
Fast Oscillator Calibration Register
On-Chip Debug Register
General Purpose I/O Register 2 General Purpose I/O Register 1 - - - - - - - - Timer/Counter0 Output Compare Register B Timer/Counter0 Output Compare Register A Timer/Counter0 (8 Bit) FOC0A COM0A1 TSM - FOC0B COM0A0 - - - COM0B1 - - - COM0B0 - - WGM02 - - - CS02 - - - CS01 WGM01 - - CS00 WGM00 PSRSYNC High Byte
92 92 92 91 88 105 19 19 19
EEPROM Address Register Low Byte EEPROM Data Register - - - - - - EEPM1 - - EEPM0 - - EERIE INT3 INTF3 EEMPE INT2 INTF2 EEPE INT1 INTF1 EERE INT0 INTF0 General Purpose I/O Register 0
19 24 57 57
238
ATmega406
2548E-AVR-07/06
ATmega406
Address
0x1B (0x3B) 0x1A (0x3A) 0x19 (0x39) 0x18 (0x38) 0x17 (0x37) 0x16 (0x36) 0x15 (0x35) 0x14 (0x34) 0x13 (0x33) 0x12 (0x32) 0x11 (0x31) 0x10 (0x30) 0x0F (0x2F) 0x0E (0x2E) 0x0D (0x2D) 0x0C (0x2C) 0x0B (0x2B) 0x0A (0x2A) 0x09 (0x29) 0x08 (0x28) 0x07 (0x27) 0x06 (0x26) 0x05 (0x25) 0x04 (0x24) 0x03 (0x23) 0x02 (0x22) 0x01 (0x21) 0x00 (0x20)
Name
PCIFR Reserved Reserved Reserved Reserved TIFR1 TIFR0 Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved PORTD DDRD PIND PORTC Reserved Reserved PORTB DDRB PINB PORTA DDRA PINA
Bit 7
- - - - - - - - - - - - - - - - - - - - - - PORTB7 DDB7 PINB7 PORTA7 DDA7 PINA7
Bit 6
- - - - - - - - - - - - - - - - - - - - - - PORTB6 DDB6 PINB6 PORTA6 DDA6 PINA6
Bit 5
- - - - - - - - - - - - - - - - - - - - - - PORTB5 DDB5 PINB5 PORTA5 DDA5 PINA5
Bit 4
- - - - - - - - - - - - - - - - - - - - - - PORTB4 DDB4 PINB4 PORTA4 DDA4 PINA4
Bit 3
- - - - - - - - - - - - - - - - - - - - - - PORTB3 DDB3 PINB3 PORTB3 DDA3 PINA3
Bit 2
- - - - - - OCF0B - - - - - - - - - - - - - - - PORTB2 DDB2 PINB2 PORTA2 DDA2 PINA2
Bit 1
PCIF1 - - - - OCF1A OCF0A - - - - - - - - - PORTD1 DDD1 PIND1 - - - PORTB1 DDB1 PINB1 PORTA1 DDA1 PINA1
Bit 0
PCIF0 - - - - TOV1 TOV0 - - - - - - - - - PORTD0 DDD0 PIND0 PORTC0 - - PORTB0 DDB0 PINB0 PORTA0 DDA0 PINA0
Page
102 94
74 74 74 76
74 74 74 73 73 73
Notes:
1. For compatibility with future devices, reserved bits should be written to zero if accessed. Reserved I/O memory addresses should never be written. 2. I/O registers within the address range $00 - $1F are directly bit-accessible using the SBI and CBI instructions. In these registers, the value of single bits can be checked by using the SBIS and SBIC instructions. 3. Some of the status flags are cleared by writing a logical one to them. Note that the CBI and SBI instructions will operate on all bits in the I/O register, writing a one back into any flag read as set, thus clearing the flag. The CBI and SBI instructions work with registers 0x00 to 0x1F only. 4. When using the I/O specific commands IN and OUT, the I/O addresses $00 - $3F must be used. When addressing I/O registers as data space using LD and ST instructions, $20 must be added to these addresses. The ATmega406 is a complex microcontroller with more peripheral units than can be supported within the 64 location reserved in Opcode for the IN and OUT instructions. For the Extended I/O space from $60 - $FF in SRAM, only the ST/STS/STD and LD/LDS/LDD instructions can be used.
239
2548E-AVR-07/06
33. Instruction Set Summary
Mnemonics
ADD ADC ADIW SUB SUBI SBC SBCI SBIW AND ANDI OR ORI EOR COM NEG SBR CBR INC DEC TST CLR SER MUL MULS MULSU FMUL FMULS FMULSU RJMP IJMP JMP RCALL ICALL CALL RET RETI CPSE CP CPC CPI SBRC SBRS SBIC SBIS BRBS BRBC BREQ BRNE BRCS BRCC BRSH BRLO BRMI BRPL BRGE BRLT BRHS BRHC BRTS BRTC BRVS BRVC Rd,Rr Rd,Rr Rd,Rr Rd,K Rr, b Rr, b P, b P, b s, k s, k k k k k k k k k k k k k k k k k k k k
Operands
Rd, Rr Rd, Rr Rdl,K Rd, Rr Rd, K Rd, Rr Rd, K Rdl,K Rd, Rr Rd, K Rd, Rr Rd, K Rd, Rr Rd Rd Rd,K Rd,K Rd Rd Rd Rd Rd Rd, Rr Rd, Rr Rd, Rr Rd, Rr Rd, Rr Rd, Rr k Add two Registers
Description
Rd Rd + Rr
Operation
Flags
Z,C,N,V,H Z,C,N,V,H Z,C,N,V,S Z,C,N,V,H Z,C,N,V,H Z,C,N,V,H Z,C,N,V,H Z,C,N,V,S Z,N,V Z,N,V Z,N,V Z,N,V Z,N,V Z,C,N,V Z,C,N,V,H Z,N,V Z,N,V Z,N,V Z,N,V Z,N,V Z,N,V None Z,C Z,C Z,C Z,C Z,C Z,C None None None None None None None I None Z, N,V,C,H Z, N,V,C,H Z, N,V,C,H None None None None None None None None None None None None None None None None None None None None None None
#Clocks
1 1 2 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 4 4 4 1/2/3 1 1 1 1/2/3 1/2/3 1/2/3 1/2/3 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2
ARITHMETIC AND LOGIC INSTRUCTIONS Add with Carry two Registers Add Immediate to Word Subtract two Registers Subtract Constant from Register Subtract with Carry two Registers Subtract with Carry Constant from Reg. Subtract Immediate from Word Logical AND Registers Logical AND Register and Constant Logical OR Registers Logical OR Register and Constant Exclusive OR Registers One's Complement Two's Complement Set Bit(s) in Register Clear Bit(s) in Register Increment Decrement Test for Zero or Minus Clear Register Set Register Multiply Unsigned Multiply Signed Multiply Signed with Unsigned Fractional Multiply Unsigned Fractional Multiply Signed Fractional Multiply Signed with Unsigned Relative Jump Indirect Jump to (Z) Direct Jump Relative Subroutine Call Indirect Call to (Z) Direct Subroutine Call Subroutine Return Interrupt Return Compare, Skip if Equal Compare Compare with Carry Compare Register with Immediate Skip if Bit in Register Cleared Skip if Bit in Register is Set Skip if Bit in I/O Register Cleared Skip if Bit in I/O Register is Set Branch if Status Flag Set Branch if Status Flag Cleared Branch if Equal Branch if Not Equal Branch if Carry Set Branch if Carry Cleared Branch if Same or Higher Branch if Lower Branch if Minus Branch if Plus Branch if Greater or Equal, Signed Branch if Less Than Zero, Signed Branch if Half Carry Flag Set Branch if Half Carry Flag Cleared Branch if T Flag Set Branch if T Flag Cleared Branch if Overflow Flag is Set Branch if Overflow Flag is Cleared Rd Rd + Rr + C Rdh:Rdl Rdh:Rdl + K Rd Rd - Rr Rd Rd - K Rd Rd - Rr - C Rd Rd - K - C Rdh:Rdl Rdh:Rdl - K Rd Rd * Rr Rd Rd * K Rd Rd v Rr Rd Rd v K Rd Rd Rr Rd 0xFF - Rd Rd 0x00 - Rd Rd Rd v K Rd Rd * (0xFF - K) Rd Rd + 1 Rd Rd - 1 Rd Rd * Rd Rd Rd Rd Rd 0xFF R1:R0 Rd x Rr R1:R0 Rd x Rr R1:R0 Rd x Rr
1 R1:R0 (Rd x Rr) << 1 R1:R0 (Rd x Rr) << 1
PC PC + k + 1 PC Z PC k PC PC + k + 1 PC Z PC k PC STACK PC STACK if (Rd = Rr) PC PC + 2 or 3 Rd - Rr Rd - Rr - C Rd - K if (Rr(b)=0) PC PC + 2 or 3 if (Rr(b)=1) PC PC + 2 or 3 if (P(b)=0) PC PC + 2 or 3 if (P(b)=1) PC PC + 2 or 3 if (SREG(s) = 1) then PCPC+k + 1 if (SREG(s) = 0) then PCPC+k + 1 if (Z = 1) then PC PC + k + 1 if (Z = 0) then PC PC + k + 1 if (C = 1) then PC PC + k + 1 if (C = 0) then PC PC + k + 1 if (C = 0) then PC PC + k + 1 if (C = 1) then PC PC + k + 1 if (N = 1) then PC PC + k + 1 if (N = 0) then PC PC + k + 1 if (N V= 0) then PC PC + k + 1 if (N V= 1) then PC PC + k + 1 if (H = 1) then PC PC + k + 1 if (H = 0) then PC PC + k + 1 if (T = 1) then PC PC + k + 1 if (T = 0) then PC PC + k + 1 if (V = 1) then PC PC + k + 1 if (V = 0) then PC PC + k + 1
R1:R0 (Rd x Rr) <<
BRANCH INSTRUCTIONS
240
ATmega406
2548E-AVR-07/06
ATmega406
33. Instruction Set Summary (Continued)
Mnemonics
BRIE BRID SBI CBI LSL LSR ROL ROR ASR SWAP BSET BCLR BST BLD SEC CLC SEN CLN SEZ CLZ SEI CLI SES CLS SEV CLV SET CLT SEH CLH DATA TRANSFER INSTRUCTIONS MOV MOVW LDI LD LD LD LD LD LD LDD LD LD LD LDD LDS ST ST ST ST ST ST STD ST ST ST STD STS LPM LPM LPM SPM IN Rd, P Rd, Z Rd, Z+ Rd, Rr Rd, Rr Rd, K Rd, X Rd, X+ Rd, - X Rd, Y Rd, Y+ Rd, - Y Rd,Y+q Rd, Z Rd, Z+ Rd, -Z Rd, Z+q Rd, k X, Rr X+, Rr - X, Rr Y, Rr Y+, Rr - Y, Rr Y+q,Rr Z, Rr Z+, Rr -Z, Rr Z+q,Rr k, Rr Move Between Registers Copy Register Word Load Immediate Load Indirect Load Indirect and Post-Inc. Load Indirect and Pre-Dec. Load Indirect Load Indirect and Post-Inc. Load Indirect and Pre-Dec. Load Indirect with Displacement Load Indirect Load Indirect and Post-Inc. Load Indirect and Pre-Dec. Load Indirect with Displacement Load Direct from SRAM Store Indirect Store Indirect and Post-Inc. Store Indirect and Pre-Dec. Store Indirect Store Indirect and Post-Inc. Store Indirect and Pre-Dec. Store Indirect with Displacement Store Indirect Store Indirect and Post-Inc. Store Indirect and Pre-Dec. Store Indirect with Displacement Store Direct to SRAM Load Program Memory Load Program Memory Load Program Memory and Post-Inc Store Program Memory In Port Rd Rr Rd+1:Rd Rr+1:Rr Rd K Rd (X) Rd (X), X X + 1 X X - 1, Rd (X) Rd (Y) Rd (Y), Y Y + 1 Y Y - 1, Rd (Y) Rd (Y + q) Rd (Z) Rd (Z), Z Z+1 Z Z - 1, Rd (Z) Rd (Z + q) Rd (k) (X) Rr (X) Rr, X X + 1 X X - 1, (X) Rr (Y) Rr (Y) Rr, Y Y + 1 Y Y - 1, (Y) Rr (Y + q) Rr (Z) Rr (Z) Rr, Z Z + 1 Z Z - 1, (Z) Rr (Z + q) Rr (k) Rr R0 (Z) Rd (Z) Rd (Z), Z Z+1 (Z) R1:R0 Rd P None None None None None None None None None None None None None None None None None None None None None None None None None None None None None None None None 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 1 k k P,b P,b Rd Rd Rd Rd Rd Rd s s Rr, b Rd, b
Operands
Description
Branch if Interrupt Enabled Branch if Interrupt Disabled Set Bit in I/O Register Clear Bit in I/O Register Logical Shift Left Logical Shift Right Rotate Left Through Carry Rotate Right Through Carry Arithmetic Shift Right Swap Nibbles Flag Set Flag Clear Bit Store from Register to T Bit load from T to Register Set Carry Clear Carry Set Negative Flag Clear Negative Flag Set Zero Flag Clear Zero Flag Global Interrupt Enable Global Interrupt Disable Set Signed Test Flag Clear Signed Test Flag Set Twos Complement Overflow. Clear Twos Complement Overflow Set T in SREG Clear T in SREG Set Half Carry Flag in SREG Clear Half Carry Flag in SREG
Operation
if ( I = 1) then PC PC + k + 1 if ( I = 0) then PC PC + k + 1 I/O(P,b) 1 I/O(P,b) 0 Rd(n+1) Rd(n), Rd(0) 0 Rd(n) Rd(n+1), Rd(7) 0 Rd(0)C,Rd(n+1) Rd(n),CRd(7) Rd(7)C,Rd(n) Rd(n+1),CRd(0) Rd(n) Rd(n+1), n=0..6 Rd(3..0)Rd(7..4),Rd(7..4)Rd(3..0) SREG(s) 1 SREG(s) 0 T Rr(b) Rd(b) T C1 C0 N1 N0 Z1 Z0 I1 I0 S1 S0 V1 V0 T1 T0 H1 H0
Flags
None None None None Z,C,N,V Z,C,N,V Z,C,N,V Z,C,N,V Z,C,N,V None SREG(s) SREG(s) T None C C N N Z Z I I S S V V T T H H
#Clocks
1/2 1/2 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
BIT AND BIT-TEST INSTRUCTIONS
241
2548E-AVR-07/06
33. Instruction Set Summary (Continued)
Mnemonics
OUT PUSH POP NOP SLEEP WDR BREAK
Operands
P, Rr Rr Rd Out Port Push Register on Stack
Description
P Rr STACK Rr Rd STACK
Operation
Flags
None None None None
#Clocks
1 2 2 1 1 1 N/A
Pop Register from Stack No Operation Sleep Watchdog Reset Break
MCU CONTROL INSTRUCTIONS (see specific descr. for Sleep function) (see specific descr. for WDR/timer) For On-chip Debug Only None None None
242
ATmega406
2548E-AVR-07/06
ATmega406
34. Ordering Information
Speed (MHz) 1 Notes: Power Supply 4.0 - 25V Ordering Code ATmega406-1AAU(2) Package(1) 48AA Operation Range Industrial (-30C to 85C)
1. This device can also be supplied in wafer form. Please contact your local Atmel sales office for detailed ordering information and minimum quantities. 2. Pb-free packaging alternative, complies to the European Directive for Restriction of Hazardous Substances (RoHS directive). Also Halide free and fully Green.
Package Type 48AA 48-lead, 7 x 7 x 1.44 mm body, 0.5 mm lead pitch, Low Profile Plastic Quad Flat Package (LQFP)
243
2548E-AVR-07/06
35. Packaging Information
35.1 48AA
PIN 1 B
PIN 1 IDENTIFIER
e
E1
E
D1 D C
0~7 A1 L
COMMON DIMENSIONS (Unit of Measure = mm) SYMBOL A A1 A2 D D1 E MIN - 0.05 1.35 8.75 6.90 8.75 6.90 0.17 0.09 0.45 NOM - - 1.40 9.00 7.00 9.00 7.00 - - - 0.50 TYP MAX 1.60 0.15 1.45 9.25 7.10 9.25 7.10 0.27 0.20 0.75 Note 2 Note 2 NOTE
A2
A
Notes:
1. This package conforms to JEDEC reference MS-026, Variation BBC. 2. Dimensions D1 and E1 do not include mold protrusion. Allowable protrusion is 0.25 mm per side. Dimensions D1 and E1 are maximum plastic body size dimensions including mold mismatch. 3. Lead coplanarity is 0.08 mm maximum.
E1 B C L e
10/5/2001 2325 Orchard Parkway San Jose, CA 95131 TITLE 48AA, 48-lead, 7 x 7 mm Body Size, 1.4 mm Body Thickness, 0.5 mm Lead Pitch, Low Profile Plastic Quad Flat Package (LQFP) DRAWING NO. 48AA REV. C
R
244
ATmega406
2548E-AVR-07/06
ATmega406
36. Errata
36.1 Rev. F
* Voltage-ADC Common Mode Offset * Voltage Reference Spike 1. Voltage-ADC Common Mode Offset The cell conversion will have an Offset-error depending on the Common Mode (CM) level. This means that the error of a cell is depending on the voltage of the lower cells. The CM Offset is calibrated away in Atmel production when the cells are balanced. When the cells get un-balanced the CM depending offset will reappear: a. Cell 1 defines its own CM level, and will never be affected by the CM dependent offset. b. c. The CM level for Cell 2 will change if Cell 1 voltage deviates from Cell 2 voltage. The CM level for Cell 3 will change if Cell 1 and/or Cell 2 voltage deviates from the voltage at Cell 3. The worst-case error is when Cell 1 and 2 are balanced while Cell 3 voltage deviates from the voltage at Cell 1 and 2.
d. The CM level for Cell 4 will change if Cell 1, Cell 2 and/or Cell 3 deviate from the voltage at Cell 4. The worst-case error is when Cell 1, Cell 2 and Cell 3 are balanced while Cell 4 voltage deviates from the voltage at Cell 1, 2 and 3. Figure 36-1 on page 246, shows the error of Cell2, Cell3 and Cell4 with 5% and 10% unbalanced cells.
245
2548E-AVR-07/06
Figure 36-1. CM Offset with unbalanced cells.
Problem Fix/Workaround Avoid getting unbalanced cells by using the internal cell balancing FETs. 2. Voltage Reference spike The Voltage Reference, VREF, will spike each time the internal temperature sensor is enabled. The temperature sensor is enabled when the VTEMP is selected in the VADMUX register and the V-ADC is enabled by the VADEN bit. The spike will be approximately 50mV and lasts for about 5ms, and it will affect any ongoing current accumulation in the CC-ADC, as well as V-ADC conversions in the period of the spike. Figure 36-2 on page 247 illustrates the Voltage Reference spike.
246
ATmega406
2548E-AVR-07/06
ATmega406
Figure 36-2. Voltage Reference Spike
Voltage
1.1 V
V~50mV
VREF
t ~< 5ms
time
VADEN
VADMUX3:0
XXX
VTEMP
Problem workaround: To get correct temperature measurement, the VADSC bit should not be written until the spike has settled (external decoupling capacitor of 1F).
247
2548E-AVR-07/06
36.2
Rev. E
* Voltage ADC not functional below 0C * Voltage-ADC Common Mode Offset * Voltage Reference Spike 1. Voltage-ADC Failing at Low Temperatures Voltage ADC not functional below 0C. The voltage ADC has a very large error below 0C, and can not be used Problem Fix/Workaround Do not use this revision below 0 celsius. 2. Voltage-ADC Common Mode Offset The cell conversion will have an Offset-error depending on the Common Mode (CM) level. This means that the error of a cell is depending on the voltage of the lower cells. The CM Offset is calibrated away in Atmel production when the cells are balanced. When the cells get un-balanced the CM depending offset will reappear: a. Cell 1 defines its own CM level, and will never be affected by the CM dependent offset. b. c. The CM level for Cell 2 will change if Cell 1 voltage deviates from Cell 2 voltage. The CM level for Cell 3 will change if Cell 1 and/or Cell 2 voltage deviates from the voltage at Cell 3. The worst-case error is when Cell 1 and 2 are balanced while Cell 3 voltage deviates from the voltage at Cell 1 and 2.
d. The CM level for Cell 4 will change if Cell 1, Cell 2 and/or Cell 3 deviate from the voltage at Cell 4. The worst-case error is when Cell 1, Cell 2 and Cell 3 are balanced while Cell 4 voltage deviates from the voltage at Cell 1, 2 and 3. Figure 36-1 on page 246, shows the error of Cell2, Cell3 and Cell4 with 5% and 10% unbalanced cells.
248
ATmega406
2548E-AVR-07/06
ATmega406
Figure 36-3. CM Offset with unbalanced cells.
Problem Fix/Workaround Avoid getting unbalanced cells by using the internal cell balancing FETs. 3. Voltage Reference Spike The Voltage Reference, VREF, will spike each time a temperature measurement is started with the Voltage-ADC. Problem Fix/Workaround An accurate temperature measurement could be obtained by doing 10 temperature conversions immediately after each other. The first 9 results would be inaccurate, but the 10th conversion will be correct. Figure 36-4 on page 250 illustrates the spike on the Voltage Reference when doing 10 temperature conversions in a row (external decoupling capacitor of 1F).
249
2548E-AVR-07/06
Figure 36-4. Voltage Reference Spike
Voltage
1.1 V
V~50mV
VREF
t ~< 5ms
time
VADSC
(10 VTEMP conversion in a row)
VADMUX3:0
XXX
VTEMP
If the CC-ADC is doing current accumulation while the V-ADC is doing temperature measurement, both the Instantaneous and the Accumulated conversion results will be affected. The spike on VREF will be visible on 1 Accumulated Current (CADAC3...0) and 2 Instantaneous Current (CADIC1...0) conversion results.
36.3
Rev. D
* * * * * *
Voltage ADC not functional below 0C Voltage-ADC Common Mode Offset Voltage Reference Spike Voltage Regulator Start-up sequence VREF influenced by MCU state EEPROM read from application code does not work in Lock Bit Mode 3
1. Voltage-ADC Failing at Low Temperatures Voltage ADC not functional below 0C. The voltage ADC has a very large error below 0C, and can not be used Problem Fix/Workaround 1. Voltage-ADC Common Mode Offset The cell conversion will have an Offset-error depending on the Common Mode (CM) level. This means that the error of a cell is depending on the voltage of the lower cells. The CM Offset is calibrated away in Atmel production when the cells are balanced. When the cells get un-balanced the CM depending offset will reappear:
250
ATmega406
2548E-AVR-07/06
ATmega406
a. Cell 1 defines its own CM level, and will never be affected by the CM dependent offset. b. c. The CM level for Cell 2 will change if Cell 1 voltage deviates from Cell 2 voltage. The CM level for Cell 3 will change if Cell 1 and/or Cell 2 voltage deviates from the voltage at Cell 3. The worst-case error is when Cell 1 and 2 are balanced while Cell 3 voltage deviates from the voltage at Cell 1 and 2.
d. The CM level for Cell 4 will change if Cell 1, Cell 2 and/or Cell 3 deviate from the voltage at Cell 4. The worst-case error is when Cell 1, Cell 2 and Cell 3 are balanced while Cell 4 voltage deviates from the voltage at Cell 1, 2 and 3. Figure 36-1 on page 246, shows the error of Cell2, Cell3 and Cell4 with 5% and 10% unbalanced cells. Figure 36-5. CM Offset with unbalanced cells.
Problem Fix/Workaround Avoid getting unbalanced cells by using the internal cell balancing FETs.
251
2548E-AVR-07/06
3. Voltage Reference Spike The Voltage Reference, VREF, will spike each time a temperature measurement is started with the Voltage-ADC. Problem Fix/Workaround An accurate temperature measurement could be obtained by doing 10 temperature conversions immediately after each other. The first 9 results would be inaccurate, but the 10th conversion will be correct. Figure 36-6 illustrates the spike on the Voltage Reference when doing 10 temperature conversions in a row (external decoupling capacitor of 1F). Figure 36-6. Voltage Reference Spike
Voltage
1.1 V
V~50mV
VREF
t ~< 5ms
time
VADSC
(10 VTEMP conversion in a row)
VADMUX3:0
XXX
VTEMP
If the CC-ADC is doing current accumulation while the V-ADC is doing temperature measurement, both the Instantaneous and the Accumulated conversion results will be affected. The spike on VREF will be visible on 1 Accumulated Current (CADAC3...0) and 2 Instantaneous Current (CADIC1...0) conversion results.
252
ATmega406
2548E-AVR-07/06
ATmega406
4. Voltage Regulator Start-up sequence When powering up ATmega406 some precautions are necessary to ensure proper start-up of the Voltage Regulator. Problem Fix/Workaround The three steps below are needed to ensure proper start-up of the voltage regulator. a. Do NOT connect a capacitor larger than 100 nF on the VFET pin. This is to ensure fast rise time on the VFET pin when a supply voltage is connected. b. During assembly, always connect Cell1 first, then Cell2 and so on until the top cell is connected to PVT. If the cell voltages are about 2 volts or larger, the Voltage Regulator will normally start up properly in Power-off mode (VREG appr. 2.8 volts). After all cells have been assembled as described in step 2, a charger source must be connected at the BATT+ terminal to initialize the chip, see Section 8.3 "Power-on Reset and Charger Connect" on page 38 in the datasheet.
c.
If the Voltage Regulator started up in Power-off during assembly of the cells, the chip will initialize when the charger source makes the voltage at the BATT pin exceed 7 - 8 Volts. If the Voltage Regulator did not start up properly, the charger source has one additional requirement to ensure proper start up and initialization. In this case the charger source must ensure that the voltage at the VFET pin increases quickly at least 3 Volts above the voltage at the PVT pin, and that the voltage at the BATT pin exceeds 7 - 8 Volts. This will start up and initialize the chip directly. 5. VREF influenced by MCU state The reference voltage at the VREF pin depends on the following conditions of the device: a. Charger Over-current and/or Discharge Over-current Protection active but Short-circuit inactive. This will increase VREF voltage with typical 1 mV compared to a condition were all Current Protections are disabled. b. Short-circuit Protection active. Short-circuit measurements are activated when SCD in BPCR is zero (default) and DFE in FET Control and Status Register (FCSR) is set. This will increase VREF voltage with typical 8 mV compared to a condition with shortcircuit measurements inactive. V-ADC conversion of the internal VTEMP voltage. This will increase VREF voltage with typical 15 mV compared to a condition with short-circuit measurements inactive.
c.
Problem Fix/Work around To ensure the highest accuracy, set the Bandgap Calibration Register (BGCC) to get 1.100 V at VREF after the chip is configured with the actual Battery Protection settings and the Discharge FET is enabled. 6. EEPROM read from application code does not work in Lock Bit Mode 3 When the Memory Lock Bits LB2 and LB1 are programmed to mode 3, EEPROM read does not work from the application code. Problem Fix/Work around Do not set Lock Bit Protection Mode 3 when the application code needs to read from EEPROM.
253
2548E-AVR-07/06
37. Datasheet Revision History
37.1 Rev 2548E - 07/06
1. 2. 3. 4. 5 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23 24. 25. 26 27. 28. 29. Updated "Pin Configurations" on page 2. Updated "ADC Noise Reduction Mode" on page 32. Updated "Power-save Mode" on page 32. Updated "Power-down Mode" on page 33. Updated "Power-off Mode" on page 33. Updated "Power Reduction Register" on page 36. Added "Voltage ADC" on page 37 and "Coloumb Counter" on page 38. Updated "Reset Sources" on page 39. Updated "Power-on Reset and Charger Connect" on page 40. Updated "External Reset" on page 41. VCC replaced by VREG in "Brown-out Detection" on page 42. Updated "Alternate Port Functions" on page 66. Updated "Internal Clock Source" on page 103. Updated "External Clock Source" on page 103. Updated Features in "Coulomb Counter - Dedicated Fuel Gauging Sigma-delta ADC" on page 106. Updated Operation in Section 18. "Coulomb Counter - Dedicated Fuel Gauging Sigma-delta ADC" on page 106. Updated Features in "Voltage Regulator" on page 114. Updated Operation in "Voltage Regulator" on page 114. Updated Bit description in "VADCL and VADCH - The V-ADC Data Register" on page 119. Updated "Writing to Bandgap Calibration Registers" on page 122. Updated Text in "Register Description for FET Control" on page 134. Added "MCUCR - MCU Control Register" on page 176. Updated "Operating Circuit" on page 223 Updated "Electrical Characteristics" on page 225. Added "Typical Characteristics - Preliminary" on page 232. Updated "Register Summary" on page 236. Updated "Errata" on page 245. Updated Table 9-2 on page 48, Table 27-5 on page 189. Updated Figure 8-1 on page 35, Figure 9-5 on page 42, Figure 17-2 on page 104, Figure 18-2 on page 107, Figure 18-3 on page 108, Figure 19-1 on page 114, Figure 29-1 on page 223. Updated Register Adresses.
30.
254
ATmega406
2548E-AVR-07/06
ATmega406
37.2 Rev 2548D - 06/05
1. Updated Section 36. "Errata" on page 245.
37.3
Rev 2548C - 05/05
1. Updated Section 36. "Errata" on page 245.
37.4
Rev 2548B - 04/05
1. 2. 3. 4. 5. 6. 7. Typos updated, bit "PSRASY" removed, CS12:0 renamed CS1[2:0]. Removed "BGEN" bit in BGCCR register. The bandgap voltage reference is always enabled in ATmega406 revision E. Updated Figure 2-1 on page 3, Figure 6-1 on page 25, Figure 24-9 on page 137, Figure 21-1 on page 120. Updated Table 7-2 on page 33, Table 7-3 on page 34, Table 8-1 on page 38, Table 26-5 on page 181, Figure 27-1 on page 188. Updated Section 12.3.2 "Alternate Functions of Port A" on page 66 and Section 21. "Battery Protection" on page 118 description. Updated registers "External Interrupt Flag Register - EIFR" on page 55 and "Timer/Counter Control Register B - TCCR0B" on page 89. Updated Section 17.1 "Features" on page 103 and Section 17.2 "Operation" on page 103. Updated Section 19.1 "Features" on page 111. Updated Section 20.2 "Register Description for Voltage Reference and Temperature Sensor" on page 116. Updated Section 29. "Electrical Characteristics" on page 211. Updated Section 35. "Errata" on page 225.
8. 9.
255
2548E-AVR-07/06
256
ATmega406
2548E-AVR-07/06
ATmega406
Table of Contents
Features ..................................................................................................... 1 1 Pin Configurations ................................................................................... 2
1.1 Disclaimer .................................................................................................................2
2
Overview ................................................................................................... 3
2.1 Block Diagram ..........................................................................................................3 2.2 Pin Descriptions .......................................................................................................5
3 4 5
Resources ................................................................................................. 7 About Code Examples ............................................................................. 7 AVR CPU Core .......................................................................................... 8
5.1 Introduction ...............................................................................................................8 5.2 Architectural Overview .............................................................................................8 5.3 ALU - Arithmetic Logic Unit .....................................................................................9 5.4 Status Register .......................................................................................................10 5.5 General Purpose Register File ...............................................................................11 5.6 Stack Pointer ..........................................................................................................12 5.7 Instruction Execution Timing ..................................................................................13 5.8 Reset and Interrupt Handling .................................................................................14
6
AVR Memories ........................................................................................ 16
6.1 In-System Reprogrammable Flash Program Memory ............................................16 6.2 SRAM Data Memory ..............................................................................................17 6.3 EEPROM Data Memory .........................................................................................18 6.4 I/O Memory .............................................................................................................24
7
System Clock and Clock Options ......................................................... 25
7.1 Clock Systems and their Distribution ......................................................................25 7.2 Clock Sources ........................................................................................................26 7.3 Calibrated Fast RC Oscillator .................................................................................26 7.4 32 kHz Crystal Oscillator ........................................................................................27 7.5 Slow RC Oscillator .................................................................................................27 7.6 Ultra Low Power RC Oscillator ...............................................................................27 7.7 CPU, I/O, Flash, and Voltage ADC Clock ...............................................................27 7.8 Coulomb Counter ADC and Wake-up Timer Clock ................................................28 7.9 Watchdog Timer and Battery Protection Clock .......................................................28
i
2548E-AVR-07/06
7.10 Run-Time Clock Source Select ............................................................................28 7.11 Register Description .............................................................................................29
8
Power Management and Sleep Modes ................................................. 31
8.1 Idle Mode ................................................................................................................32 8.2 ADC Noise Reduction Mode ..................................................................................32 8.3 Power-save Mode ..................................................................................................32 8.4 Power-down Mode .................................................................................................33 8.5 Power-off Mode ......................................................................................................33 8.6 Power Reduction Register ......................................................................................36 8.7 Minimizing Power Consumption .............................................................................37
9
System Control and Reset .................................................................... 39
9.1 Resetting the AVR ..................................................................................................39 9.2 Reset Sources ........................................................................................................39 9.3 Watchdog Timer .....................................................................................................43 9.4 Register Description ...............................................................................................46
10 Wake-up Timer ....................................................................................... 49
10.1 Overview ..............................................................................................................49 10.2 Register Description .............................................................................................49
11 Interrupts ................................................................................................ 51
11.1 Interrupt Vectors in ATmega406 ..........................................................................51 11.2 Moving Interrupts Between Application and Boot Space .....................................54 11.3 Register Description .............................................................................................55
12 External Interrupts ................................................................................. 56
12.1 Overview ..............................................................................................................56 12.2 Register Description .............................................................................................56
13 Low Voltage I/O-Ports ............................................................................ 60
13.1 Introduction ...........................................................................................................60 13.2 Low Voltage Ports as General Digital I/O .............................................................61 13.3 Alternate Port Functions .......................................................................................66 13.4 Register Description .............................................................................................73
14 High Voltage I/O Ports ........................................................................... 75
14.1 High Voltage Ports as General Digital Outputs ....................................................75 14.2 Configuring the Pin ...............................................................................................76 14.3 Register Description for High Voltage Output Ports .............................................76 ii
ATmega406
2548E-AVR-07/06
ATmega406
15 8-bit Timer/Counter0 with PWM ............................................................ 77
15.1 Overview ..............................................................................................................77 15.2 Timer/Counter Clock Sources ..............................................................................78 15.3 Counter Unit .........................................................................................................78 15.4 Output Compare Unit ...........................................................................................79 15.5 Compare Match Output Unit .................................................................................81 15.6 Modes of Operation ..............................................................................................82 15.7 Timer/Counter Timing Diagrams ..........................................................................86 15.8 8-bit Timer/Counter Register Description .............................................................88
16 16-bit Timer/Counter1 ............................................................................ 95
16.1 Overview ..............................................................................................................95 16.2 Accessing 16-bit Registers ...................................................................................96 16.3 Timer/Counter Clock Sources ..............................................................................98 16.4 Counter Unit .........................................................................................................99 16.5 Output Compare Unit ...........................................................................................99 16.6 16-bit Timer/Counter Register Description .........................................................100
17 Timer/Counter0 and Timer/Counter1 Prescalers .............................. 103
17.1 Internal Clock Source .........................................................................................103 17.2 Prescaler Reset ..................................................................................................103 17.3 External Clock Source ........................................................................................103 17.4 Register Description ...........................................................................................105
18 Coulomb Counter - Dedicated Fuel Gauging Sigma-delta ADC ...... 106
18.1 Features .............................................................................................................106 18.2 Operation ............................................................................................................107
19 Voltage Regulator ................................................................................ 114
19.1 Features .............................................................................................................114 19.2 Operation ............................................................................................................114
20 Voltage ADC - 10-channel General Purpose 12-bit Sigma-Delta ADC .. 116
20.1 Features .............................................................................................................116 20.2 Operation ............................................................................................................117 20.3 Register Description ...........................................................................................118
21 Voltage Reference and Temperature Sensor .................................... 121
21.1 Features .............................................................................................................121
iii
2548E-AVR-07/06
21.2 Writing to Bandgap Calibration Registers ...........................................................122 21.3 Register Description for Voltage Reference and Temperature Sensor ..............123
22 Battery Protection ................................................................................ 125
22.1 Features .............................................................................................................125 22.2 Deep Under-voltage Protection ..........................................................................126 22.3 Discharge Over-current Protection .....................................................................126 22.4 Charge Over-current Protection .........................................................................126 22.5 Short-circuit Protection .......................................................................................127 22.6 Battery Protection CPU Interface .......................................................................127 22.7 Register Description for Battery Protection ........................................................128
23 FET Control .......................................................................................... 133
23.1 FET Driver ..........................................................................................................134 23.2 Register Description for FET Control ..................................................................134
24 Cell Balancing ...................................................................................... 136
24.1 Register Description ...........................................................................................137
25 2-wire Serial Interface .......................................................................... 138
25.1 Features .............................................................................................................138 25.2 Two-wire Serial Interface Bus Definition .............................................................138 25.3 Data Transfer and Frame Format .......................................................................139 25.4 Multi-master Bus Systems, Arbitration and Synchronization ..............................142 25.5 Overview of the TWI Module ..............................................................................144 25.6 TWI Register Description ...................................................................................147 25.7 Using the TWI .....................................................................................................150 25.8 Transmission Modes ..........................................................................................153 25.9 Multi-master Systems and Arbitration .................................................................167 25.10 Bus Connect/Disconnect for Two-wire Serial Interface ....................................169
26 JTAG Interface and On-chip Debug System ..................................... 171
26.1 Features .............................................................................................................171 26.2 Overview ............................................................................................................171 26.3 Test Access Port - TAP .....................................................................................171 26.4 TAP Controller ....................................................................................................173 26.5 Using the On-chip Debug System ......................................................................174 26.6 On-chip Debug Specific JTAG Instructions ........................................................175 26.7 On-chip Debug Related Register .......................................................................176
iv
ATmega406
2548E-AVR-07/06
ATmega406
26.8 Using the JTAG Programming Capabilities ........................................................177
27 Boot Loader Support - Read-While-Write Self-Programming ......... 178
27.1 Boot Loader Features .........................................................................................178 27.2 Application and Boot Loader Flash Sections ......................................................178 27.3 Read-While-Write and No Read-While-Write Flash Sections .............................179 27.4 Boot Loader Lock Bits ........................................................................................181 27.5 Entering the Boot Loader Program .....................................................................183 27.6 Addressing the Flash During Self-Programming ................................................185 27.7 Self-Programming the Flash ...............................................................................186
28 Memory Programming ......................................................................... 195
28.1 Program And Data Memory Lock Bits ................................................................195 28.2 Fuse Bits ............................................................................................................196 28.3 Signature Bytes ..................................................................................................198 28.4 Calibration Bytes ................................................................................................198 28.5 Page Size ...........................................................................................................198 28.6 Parallel Programming .........................................................................................199 28.7 Programming via the JTAG Interface .................................................................211
29 Operating Circuit .................................................................................. 223 30 Electrical Characteristics .................................................................... 225
30.1 Absolute Maximum Ratings* ..............................................................................225 30.2 DC Characteristics .............................................................................................225 30.3 General I/O Lines characteristics .......................................................................228 30.4 2-wire Serial Interface Characteristics ................................................................229 30.5 Reset Characteristics .........................................................................................230 30.6 Supply Current of I/O Modules ...........................................................................231
31 Typical Characteristics - Preliminary ................................................ 232
31.1 Pin Pull-up ..........................................................................................................232 31.2 Pin Driver Strength .............................................................................................233 31.3 Internal Oscillator Speed ....................................................................................234
32 Register Summary ............................................................................... 236 33 Instruction Set Summary .................................................................... 240 34 Ordering Information ........................................................................... 243 35 Packaging Information ........................................................................ 244
v
2548E-AVR-07/06
35.1 48AA ...................................................................................................................244
36 Errata ..................................................................................................... 245
36.1 Rev. F .................................................................................................................245 36.2 Rev. E .................................................................................................................248 36.3 Rev. D ................................................................................................................250
37 Datasheet Revision History ................................................................ 254
37.1 Rev 2548E - 07/06 .............................................................................................254 37.2 Rev 2548D - 06/05 .............................................................................................255 37.3 Rev 2548C - 05/05 .............................................................................................255 37.4 Rev 2548B - 04/05 .............................................................................................255
Table of Contents....................................................................................... i
vi
ATmega406
2548E-AVR-07/06
Atmel Corporation
2325 Orchard Parkway San Jose, CA 95131, USA Tel: 1(408) 441-0311 Fax: 1(408) 487-2600
Atmel Operations
Memory
2325 Orchard Parkway San Jose, CA 95131, USA Tel: 1(408) 441-0311 Fax: 1(408) 436-4314
RF/Automotive
Theresienstrasse 2 Postfach 3535 74025 Heilbronn, Germany Tel: (49) 71-31-67-0 Fax: (49) 71-31-67-2340 1150 East Cheyenne Mtn. Blvd. Colorado Springs, CO 80906, USA Tel: 1(719) 576-3300 Fax: 1(719) 540-1759
Regional Headquarters
Europe
Atmel Sarl Route des Arsenaux 41 Case Postale 80 CH-1705 Fribourg Switzerland Tel: (41) 26-426-5555 Fax: (41) 26-426-5500
Microcontrollers
2325 Orchard Parkway San Jose, CA 95131, USA Tel: 1(408) 441-0311 Fax: 1(408) 436-4314 La Chantrerie BP 70602 44306 Nantes Cedex 3, France Tel: (33) 2-40-18-18-18 Fax: (33) 2-40-18-19-60
Biometrics/Imaging/Hi-Rel MPU/ High Speed Converters/RF Datacom
Avenue de Rochepleine BP 123 38521 Saint-Egreve Cedex, France Tel: (33) 4-76-58-30-00 Fax: (33) 4-76-58-34-80
Asia
Room 1219 Chinachem Golden Plaza 77 Mody Road Tsimshatsui East Kowloon Hong Kong Tel: (852) 2721-9778 Fax: (852) 2722-1369
ASIC/ASSP/Smart Cards
Zone Industrielle 13106 Rousset Cedex, France Tel: (33) 4-42-53-60-00 Fax: (33) 4-42-53-60-01 1150 East Cheyenne Mtn. Blvd. Colorado Springs, CO 80906, USA Tel: 1(719) 576-3300 Fax: 1(719) 540-1759 Scottish Enterprise Technology Park Maxwell Building East Kilbride G75 0QR, Scotland Tel: (44) 1355-803-000 Fax: (44) 1355-242-743
Japan
9F, Tonetsu Shinkawa Bldg. 1-24-8 Shinkawa Chuo-ku, Tokyo 104-0033 Japan Tel: (81) 3-3523-3551 Fax: (81) 3-3523-7581
Literature Requests
www.atmel.com/literature
Disclaimer: The information in this document is provided in connection with Atmel products. No license, express or implied, by estoppel or otherwise, to any intellectual property right is granted by this document or in connection with the sale of Atmel products. EXCEPT AS SET FORTH IN ATMEL'S TERMS AND CONDITIONS OF SALE LOCATED ON ATMEL'S WEB SITE, ATMEL ASSUMES NO LIABILITY WHATSOEVER AND DISCLAIMS ANY EXPRESS, IMPLIED OR STATUTORY WARRANTY RELATING TO ITS PRODUCTS INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE, SPECIAL OR INCIDENTAL DAMAGES (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF PROFITS, BUSINESS INTERRUPTION, OR LOSS OF INFORMATION) ARISING OUT OF THE USE OR INABILITY TO USE THIS DOCUMENT, EVEN IF ATMEL HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Atmel makes no representations or warranties with respect to the accuracy or completeness of the contents of this document and reserves the right to make changes to specifications and product descriptions at any time without notice. Atmel does not make any commitment to update the information contained herein. Atmel's products are not intended, authorized, or warranted for use as components in applications intended to support or sustain life.
(c) 2006 Atmel Corporation. All rights reserved. ATMEL (R), logo and combinations thereof, Everywhere You Are (R), AVR (R), and AVR Studio (R) are the registered trademarks of Atmel Corporation or its subsidiaries. Other terms and product names may be trademarks of others.
2548E-AVR-07/06


▲Up To Search▲   

 
Price & Availability of ATMEGA4060607

All Rights Reserved © IC-ON-LINE 2003 - 2022  

[Add Bookmark] [Contact Us] [Link exchange] [Privacy policy]
Mirror Sites :  [www.datasheet.hk]   [www.maxim4u.com]  [www.ic-on-line.cn] [www.ic-on-line.com] [www.ic-on-line.net] [www.alldatasheet.com.cn] [www.gdcy.com]  [www.gdcy.net]


 . . . . .
  We use cookies to deliver the best possible web experience and assist with our advertising efforts. By continuing to use this site, you consent to the use of cookies. For more information on cookies, please take a look at our Privacy Policy. X